213 total views, 1 views today
Welcome to Scala series.In this tutorial, you will learn about Scala tuple in detail.
A tuple is a collection of elements with different data types. We can consider a Tuple as a bag of any elements or a container of elements.
Tuple is a powerful structure and one of the key feature of Scala.
It is a generic object and doesn’t belong to any data type. But it can have a collection of elements with different data types.
Each element in the tuple can be accessed with underscore notation.
Tuple represents a record with elements of heterogeneous type.
Tuples are immutable. Which means once tuple is created we cannot modify the number of elements in the tuple nor the type of the elements.
It is mainly useful for returning multiple values from a method. Usually, we will create a class for returning multiple elements, but tuple is the easiest and best way to be used for returning multiple elements.
Tuple is replacement of creating classes for passing through the method. Because, when we create a class, we need to create an object and assign the variables and pass it.
Tuple is itself a Type but it depends on the number of elements in the tuple.
Let us now create a Tuple with two elements.
scala> val tuple = (1,"Raj") tuple: (Int, String) = (1,Raj)
To access each element of the tuple.
The above example is a 2-element tuple. This can also be written as below.
scala> val tuple = Tuple2(1,"") tuple: (Int, String) = (1,"")
If you notice,Tuple2 class has been used. Tuple is a class it is based on the number of elements.
In Scala, we have many classes of Tuple starting from Tuple2, Tuple3, Tuple4….Tuple22.Each number in the class name is the number of elements the corresponding class supports.
var tuple2 = Tuple2(1, "abc") println(tuple2._1) println(tuple2._2)
var tuple3 = Tuple3(1, "abc", 12.0) println(tuple3._1) println(tuple3._2) println(tuple3._3)
var tuple4 = Tuple4(1, "abc", 12.0, 11.0f) println(tuple4._1) println(tuple4._2) println(tuple4._3) println(tuple4._4)
References: Official documentation
Please leave a comment and give us a thumbs up!.