Scala Language 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:

scala> val l = List(1 -> 2, 2 -> 3, 3 -> 4)
l: List[(Int, Int)] = List((1,2), (2,3), (3,4))

It may seem natural to add the elements together using implicit tuple-unpacking:

scala> Int, e2: Int) => e1 + e2)

However this results in the following error:

<console>:9: error: type mismatch;
 found   : (Int, Int) => Int
 required: ((Int, Int)) => ?
     Int, e2: Int) => e1 + e2)

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:

scala> => e._1 + e._2)
res1: List[Int] = List(3, 5, 7)

The other option is to use a case statement to unpack the tuples using pattern matching:

scala>{ case (e1: Int, e2: Int) => e1 + e2}
res2: List[Int] = List(3, 5, 7)

These restrictions apply for any higher-order-function applied to a collection of tuples.