A tuple in Scala is an immutable sequence of values of multiple types.

(x, y) is known as a pair in Scala.
A Pair is a Tuple of size 2.

Creating a tuple

Most common way . e.g (“ABC”, 42)
Using -> operator. eg. “ABC” -> 42, creates a tuple (“ABC”, 42)

 

A Tuple Type (T1, …, Tn) is abbreviation of the parameterized type scala.Tuple(n)[T1,…Tn].

A Tuple expression (e1, …, en) is equivalent to the function application scala.Tuple(n)(e1,…en).

A Tuple Pattern (p1, …, pn) is equivalent to the constructor pattern scala.Tuple(n)(p1,…pn)

 

A tuple isn’t actually a collection; it’s a series of classes named Tuple2, Tuple3, etc., through Tuple22. e.g Tuple2 is modeled as

case class Tuple2[T1, T2](_1: T1, _2: T2) { 
  override def toString = "(" + _1 + "," + _2 + ")" 
}

 

Accessing elements of a Pair/Tuple2

e.g

 val pair: (String, Int) = ("ABC", 42)

By _n

val name:String = pair._1 
val age: Int = pair._2

Pattern Matching/ Extractor

val (name:String, age:Int) = pair

 

Pattern Matching in Pair/Tuples

(x, y) match { 
  case ("ABC", _) => println("ABC is found") 
  case (_, age) if age > 30 => println("age is greater than 30") 
  case (x:String, y:Int) => println (s"$x , $y") 
  case _ => println("Invalid scenario")
}

Iterating over a Scala tuple

Although, a tuple is not a collection, but you can still iterate over its elements (just like a collection) using its productIterator method.

val test = ("Demo", 100.5, 76) 
test.productIterator.foreach(println)
//100.5
//76

 

 

References

https://alvinalexander.com/scala/scala-tuple-examples-syntax

https://www.coursera.org/learn/progfun1/home/welcome