Tuple in Scala
Posted January 17, 2013on:
Tuple in Scala
Before start with Scala tuple we go through what is Tuple in general term. In mathematical terms Tuple is list of ordered and unordered elements. For example if you say n-tuple, your tuple contains n numbers of elements as your tuple values. Scala tuple also having for the same purpose and added powerful feature to the Scala language. As I mentioned my previous blog Scala emphasise functional programing language and they force to provide immutable collections and in Scala tuples are immutable like List and only different between list and tuples, tuples contains collection of different type.
- Declare tuple in Scala
You can create tuple using above image, either writing simple list of elements or by creating object using new keyword. In above tuple I have created 3 element size tuple and while creating tuple I have used “new Tuple3” and in that 3 signify 3 elements size tuple. Scala gives you facility to create up to 22 size elements tuple using “new Tuple22” and if you try to create tuple with size more than 22 elements compiler gives you error like “error: not found: type Tuple”. If you see above image you will notice Scala automatically identify the type of tuple elements how you provide as tuple value. Now you see how to declare tuple but yes you have a question why we need the tuples, let’s take an example where you need your method return multiple values and in that case in java you have to declare a POJO class and return as part of your method return type. Now in Scala you can return tuple instead of your POJO class and you can do this simple thing by creating just tuple.
- Access tuple elements in Scala
Once you declare elements in tuple you can access it using dot, underscore and element index. For detail see below image,
So as in above image to access 1st element in tuple I have used tuple._1 which will return first element of the define tuple and same for others what I have to do is change in index number and I will have indexed tuple value.
Now if you aware of Scala or java collection you might having question why we have to use dot, underscore and tuple element index to access the values from tuple. Now in Scala when you write tuple(1) Scala complier call apply method and if you see Scala API apply method always return same type of elements and as I said earlier, Scala tuple is collection of different type of elements.