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

scala> val x = (1, "hello") 
x: (Int, String) = (1,hello)
scala> val y = 2 -> "world" 
y: (Int, String) = (2,world)
scala> val z = 3 → "foo"     //example of using U+2192 RIGHTWARD ARROW
z: (Int, String) = (3,foo)

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:

scala> val m = Map[Int, String](2 -> "world")
m: scala.collection.immutable.Map[Int,String] = Map(2 -> world)

scala> m + x
res0: scala.collection.immutable.Map[Int,String] = Map(2 -> world, 1 -> hello)

scala> (m + x).toList
res1: List[(Int, String)] = List((2,world), (1,hello))

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.