In mathematics and computer science, a tuple is an ordered list of elements. In set theory, an (ordered) n-tuple is a sequence (or ordered list) of n elements, where n is a positive integer.
So, for example, in Python the 2nd item of a tuple would be accessed via t[1]
.
In Scala, access is only possible via strange names t._2
.
So the question is, why can't I access data in tuples as Sequence or List if it is by definition? Is there some sort of idea or just yet not inspected?
Tuples and lists are the same in every way except two: tuples use parentheses instead of square brackets, and the items in tuples cannot be modified (but the items in lists can be modified). We often call lists mutable (meaning they can be changed) and tuples immutable (meaning they cannot be changed).
In Scala, a tuple is a value that contains a fixed number of elements, each with its own type. Tuples are immutable. Tuples are especially handy for returning multiple values from a method.
Tuple. The word “tuple” means “a data structure consisting of multiple parts”. Hence Tuples can be defined as a data structure that can hold multiple values and these values may/may not be related to each other. Example: [Geeks, 123, &#*@]
Why are tuples so bad? The bigger problems of using tuples: Usually, you can't easily understand what each tuple field means without getting a lot of context. This probably includes trace back until the moment the tuple was created.
Scala knows the arity of the tuples and is thus able to provide accessors like _1
, _2
, etc., and produce a compile-time error if you select _3
on a pair, for instance. Moreover, the type of those fields is exactly what the type used as parameter for Tuple
(e.g. _3
on a Tuple3[Int, Double, Float]
will return a Float
).
If you want to access the nth element, you can write tuple.productElement(n)
, but the return type of this can only be Any
, so you lose the type information.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With