Creating a new Tuple
A tuple is a heterogeneous collection of two to twenty-two values. A tuple can be defined using parentheses. For tuples of size 2 (also called a 'pair') there's an arrow syntax.
x is a tuple of size two. To access the elements of a tuple use ._1, through ._22. For instance, we can use x._1 to access the first element of the x tuple. x._2 accesses the second element. More elegantly, you can use tuple extractors.
The arrow syntax for creating tuples of size two is primarily used in Maps, which are collections of (key -> value) pairs:
The syntax for the pair in the map is the arrow syntax, making it clear that 1 is the key and a is the value associated with that key.
Tuples within Collections
Tuples are often used within collections but they must be handled in a specific way. For example, given the following list of tuples:
It may seem natural to add the elements together using implicit tuple-unpacking:
However this results in the following error:
Scala cannot implicitly unpack the tuples in this manner. We have two options to fix this map. The first is to use the positional accessors _1 and _2:
The other option is to use a case statement to unpack the tuples using pattern matching:
These restrictions apply for any higher-order-function applied to a collection of tuples.