Hey Folks, back after a good amount of time and No….. was not on vacations, but working on some very critical deliverable.

So What did I do the last one and half month, learned more Scala and Spark… its getting interesting day by day and I have already learnt a lot of stuff, that can be shared through by posts here…. so stay tuned…. there is good information coming along.

So Tuples ……

What are Tuples
They are
1. List like objects
2. Are immutable
3. Contains a fixed number of elements
4. Can contain elements of different type.

If they are like Lists, whats the advantage
1. They are type safe, you can add any type of element to tuple
2. Ease of use

Declaring Tuples

val (name, id) = ("abc", 1)
val detailTup = ("abc", 1)

Above, I declared 2 tuples, the first one we can directly access variables using the name of the variables like “id”. Second one, we can access it using index position.

Using Tuples and accessing its elements

val detailTup = ("abc", 1)


detailTup: (String, Int) = (abc,1)

As shown above, we can use index position and get the values from Tuples directly.

Best Use case , when to use tuples
I came across a scenario where based on some condition, I had to assign some values to variables, Traditionally I could have done using some IF statements, but the other way recommended to me by our Scala expert, was to use Tuples.

Using tuples, we can quickly assign conditional values to multiple variables directly. Its a mix of CASE construct and tuples assignment. Due to functional behavior of Scala, every case command is a able to return a tuple here and the returned tuple gets mapped to Variables as shown.

val fruit = "apple"

val (color, taste, seedless) = fruit match {
    case "apple" => ("red","sweet",1)
    case "orange" => ("orange","sour",0)


fruit: String = apple
color: String = red
taste: String = sweet
seedless: Int = 1

In the above example, I created a tuple with 3 variables (color, taste, seedless) the first, 2 variables are String Type, but last one is int type.
Then before assigning the value to these variables, I checked which fruit it is and accordingly assigned values to the variables, every case statement here returns a tuple.

Tuples can be extensively used for different scenario, you can even try to use VAR with tuples for more flexibility.
Over all using Tuples, helped me reduce the lines of code, when writing complex scala programs.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s