In Scala, a tuple is a class that gives us a simple way to store heterogeneous items or different data types in the same container. A tuples purpose is to combine a fixed and finite number of items together to allow the programmer to pass a tuple as a whole. A tuple is immutable in Scala. Click here to know more about mutability and immutability. An example of a tuple storing an integer, and a string value.

val t = (1, "hello world")

which is a syntactic sugar for the following-

val t = new Tuple2(1, "hello world")

The type of a tuple depends upon the number of elements it contains and the types of those elements. Thus, the type of (1, “hello world”) is Tuple2[Int, String]. Tuples can be of type Tuple1, Tuple2, Tuple3 and so on. Currently there is an upper limit of 22 in the Scala and if we need more, then we will have to use a collection, not a tuple.

Operations on Scala Tuple

Access element from tuple

One approach is to access them by element number, where the number is preceded by an underscore, method tuple._i is used to access the ith element of the tuple.

Pattern matching on Scala tuples

The another approach to access elements of a tuple is pattern-matching. It is a great way to assign tuple elements to variables. Pattern matching is a mechanism for checking a value against a pattern.

Another Example for pattern-matching a tuple:

val relation =
  List(("Bob", "Father"), ("Jack", "Brother"), ("Rock", "Friend"))
relation.foreach{
  case ("Jack", relation) =>
    println(s"Jack is $relation of Alice")
  case ("Bob", relation) =>
    println(s"Bob is $relation of Alice")
  case _ => println(relation(2)._1 + " has wrong relation with Alice")
}

The output for above code will be:

Bob is Father of Alice

Jack is Brother of Alice

Rock has wrong relation with Alice

#scala #tuples

A tour to the Scala Tuples
1.85 GEEK