Scala tuple in detail

 213 total views,  1 views today

Welcome to Scala series.In this tutorial, you will learn about Scala tuple in detail.

Scala Tuple

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.

println(tuple._1)
println(tuple._2)

Output

1
Raj

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.

Tuple2 Example

 var tuple2 = Tuple2(1, "abc")

 println(tuple2._1)
 println(tuple2._2)

Tuple3 Example

var tuple3 = Tuple3(1, "abc", 12.0)

println(tuple3._1)
println(tuple3._2)
println(tuple3._3)

Tuple4 Example

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!.

Tags :

About the Author

Rajasekar

Hey There, My name is Rajasekar and I am the author of this site. I hope you are liking my tutorials and references. Programming and learning new technologies are my passion. The ultimate idea of this site is to share my knowledge(I am still a learner :)) and help you out!. Please spread your words about us (staticreference.com) and give a thumbs up :) Feel free to contact me for any queries!.