I Like Tuples in Scala. I’m almost as happy as when I met Ranges in Groovy/Ruby. My main programming language is Java and there aren’t such nice control structures.

Then, what is Tuple?

Tuple in Scala is part of the Collections API.
Tuple combines a fixed number of items together and all can be used as one object. Tuples can hold objects with different types (unlike an array or list) and are immutable.

What means Tuple is collection with fixed size?

Every Tuple you define is one of the class :Tuple2, Tuple3, …,Tuple22 .The number in name of class is an amount of items this object can hold. Then if you use Tuple3 class, you can hold only 3 items in it. And yes, upper limit is 22 because there is no Tuple23 class in API.

How to use it:

The standard way is new object invocation from class:

Example above show us tuple that holds Integer, Boolean and String.
But there are the simplest way. In fact, you no need to invoke a class. You just put all items inside rounded braces:

The actual type of a tuple depends upon the number and of elements it contains and the types of those elements. Thus, the type of (99, „none”) is Tuple2[Int, String].

Tuples are collections and you can access any element in it. Scala provides elements-access methods for every tuple class. To access elements of a tuple t, you can use method t._1 to access the first element, t._2 to access the second, and so on.

There is an iterator for iterate over collection. You get it by use Tuple.productIterator() method.

Convert to String

Tuples override toString() method to pretty print what it contains:

Tuple2

Class Tuple2 has few differences between other tuples. Two are worth few words.
First, most important, is another type of declaration. We can use -> as separator both elements.

this method you see new Map is invoked.

Another addition is swap method.
Tuple2 has a method Tuple2.swap that swaps elements, for example:

Remember the swap method is only in the Tuple2 class.

Where can I use Tuples?

Anywhere! In fact you use tuples when you use Maps. All elements in maps are stored as Tuple2, (example from REPL):

You can use tuples to assign multiple variables at once:

.