All you need to know about tuples in Scala

What is tuple in Scala?

Tuple in Scala is an immutable collection of fixed number of heterogeneous elements. Tuples are not mutable, which means once a tuple is defined we cannot change values in it and can hold elements of different data types whereas an array is mutable and holds elements of same data type.


How can we create tuples?

We create tuples in Scala as shown below:

val tuple1 = ("hello", 1, Console)    //Without datatypes
val tuple2: (String, Int) = ("abc",1) //It is not mandatory to supply data types

As you can see in the above code, we have created a tuple with a string, integer and class types in it.

We can access elements of tuples using the methods _1, _2 and etc. Here _1 gives us the first, _2 to gives us second element and so on. In Scala3 we can also use index to access elements similar to lists.

val tuple = ("Hello", 1)

How do we iterate over the tuple?

To iterate over a tuple we can use Tuple.productIterator() method as show below:

val tuple = ("hello", 1, Console);
tuple.productIterator.foreach(x => println(x))


How can we use tuples ?

1). When we want to return multiple values of different data types from a method then we can go for tuples.

For ex:

def getSalesDetails = { 
    // other code here ... 
    ("PRODUCT1", 1, 101.00)  

Above method returns a of size 3 elements.

2). We can use tuples to assign values to multiple variables using pattern matching as shown below:

val (studentName, marks) = ("Ravi", 100)


Note: Scala tuples are not collections, so they won't support traditional collections methods like map, filter, etc.

Leave a Reply

Your email address will not be published. Required fields are marked *