Tuples in Scala – A Quick Introduction


1. Objective

This tutorial will help you in understanding the concept of tuples in Scala programming language. You will learn creating scala tuples with examples and syntax. You will also learn iteration over the tuples in scala, swapping of tuple elements and way to convert tuple into string in scala function. Before starting with Scala tuples, let us brush our Scala concepts and features of Scala that make it so popular and create comparison between Java and Scala.

Tuples in Scala

2. Introduction to Tuples in Scala

Tuple is a Scala collection which can hold multiple values of same or different type together so they can be passed around as a whole. Unlike an array or list, a tuple can hold objects with different types but they are also immutable.

Let us understand the same with an example of tuple holding an integer, a string, and a double:

val t = new Tuple3(1, "hello",20.2356)

A short cut for the above code is :-

val t = (1, "hello",20.2356)

You can also create a tuple using the below syntax:

1 -> “a”

This syntax would be seen a lot when creating maps.

The actual type of a tuple depends upon the number of elements it contains and the type of those elements. Thus the type of (1,”hello”,20.2356) is Tuple3[Int , String , Double].Tuple are of type Tuple1 , Tuple2 ,Tuple3 and so on. There is an upper limit of 22 for the element in the tuple in the scala, if you need more elements, then you can use a collection, not a tuple.

For each tuple type, Scala defines a number of element access methods.

Examples:

val t = (4,3,2,1)
val sum = t._1 + t._2 + t._3 + t._4
println( "Sum of elements: " + sum ) 

// Sum of elements : 10

3. Iteration over the tuple

You can use Tuple.productIterator() method to iterate over all of the elements of a tuple.

Example:

val t = (4,3,2,1)
t.productIterator.foreach{ i => println("Value = " + i )} 

Output

Value = 4
Value = 3
Value = 2
Value = 1

4. Swapping of tuple elements

We can perform swapping of tuple elements by using tuple.swap method.

Example

val t = new Tuple2("tuple", "test")
println("Swapped Tuple: " + t.swap )

Output

Swapped tuple: (test,tuple)

5. Converting tuple to String:

We can use tuple.toString() method to concatenate elements of tuple to string.

Example:

val t = (1, "hello",20.2356)
println("Concatenated String: " + t.toString() )

Output

Concatenated String:(1, hello,20.2356)

For further Scala knowledge, refer Best Scala books for beginners

Leave a comment

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