Scala tuples are used to combine a fixed number of items together. The ultimate target of this grouping is to help in the anonymous function and so that they can be passed around as a whole. The real difference with an array or list is that a tuple can hold objects of different types while maintaining the information of the type of each element, while a collection doesn't and uses, as the type, the common type (for instance, in the previous example, the type of that set would be Set[Any]).
From the computational point of view, Scala tuples are also immutable. In other words, Tuples do use a classes to store elements (for example, Tuple2, Tuple3, Tuple22, and so on).
The following is an example of a tuple holding an integer, a string, and the console:
val tuple_1 = (20, "Hello", Console)
Which is syntactic sugar (shortcut) for the following:
val t = new Tuple3(20, "Hello", Console)
Another example:
scala> val cityPop = ("Dublin", 2)
cityPop: (String, Int) = (Dublin,2)
There are no named accessors for you to access the tuple data but instead you need to use accessors that are based on the position and are 1-based not 0-based. For example:
scala> val cityPop = ("Dublin", 2)
cityPop: (String, Int) = (Dublin,2)
scala> cityPop._1
res3: String = Dublin
scala> cityPop._2
res4: Int = 2
Moreover, tuples can fit perfectly in pattern matching. For example:
cityPop match {
case ("Dublin", population) => ...
case ("NY", population) => ...
}
You can even use the special operator -> in order to write a compact syntax for 2-values tuples. For example:
scala> "Dublin" -> 2
res0: (String, Int) = (Dublin,2)
The following is a more detailed example to demonstrate tuple functionality:
package com.chapter4.CollectionAPI
object TupleExample {
def main(args: Array[String]) {
val evenTuple = (2,4,6,8)
val sumTupleElements =evenTuple._1 + evenTuple._2 + evenTuple._3 + evenTuple._4
println( "Sum of Tuple Elements: " + sumTupleElements )
// You can also iterate over the tuple and print it's element using the foreach method
evenTuple.productIterator.foreach{ evenTuple =>println("Value = " + evenTuple )}
}
}
You will get the following output:
Sum of Tuple Elements: 20 Value = 2 Value = 4 Value = 6 Value = 8
Now, let's delve into the world of using maps in Scala, these are widely used to hold basic datatypes.