Combating Fallacy in Scala: Part 2

Combating Fallacy in Scala
Reading Time: 3 minutes

Welcome back to this amazing series of Combating Fallacy in Scala: Part 2. For this part, the topic will be “Tuple Unpacking”. So, let’s move forward.

Tuple Unpacking

Before looking into this, let’s have a look at Tuple in Scala.

According to the Scala Docs “A tuple is a neat class that gives you a simple way to store heterogeneous (different) items in the same container.

A tuple provides us with a container that can store different types of values. It can have up to 22 elements.

Let’s look at an example of a tuple:

Tuple example

And this is how we access the values:

Accessing values in tuple

Now, what if we don’t want to access the variables in the way shown in the above picture?

The other way could be doing tuple unpacking. In this, we bind every value in the tuple with a variable/reference. This is done using Pattern Matching internally.

Now, we will look at a situation and I’ll give you some options so that we can figure out the correct way of doing tuple unpacking. Consider, we have a tuple containing name and age of the person and I want to access both of them individually.

Here is that tuple :


Option 1:

option 1

Option 2:

option 2

Option 3:

option 3

What do you think? Are all of them correct or should Option 2 and 3 both work?

Time to Reveal

The correct option is Option 3.

You might think why not the second one or the first. So, the reasons are the following:

correct option
  • Option 1 is simply an assignment operation. Now the value in “nany” will be the same as in “tuple”.
result of option 1
  • Option 2, is a way to assign the same expression to multiple variables.
result of option 2

Now, I hope that from next time you will avoid this small mistake. That’s all for this blog. You can also visit the previous blog in this series, Combating Fallacy in Scala: Part 1. Do share your feedback in the comment section below.

Written by 

Muskan Gupta is a Software Consultant having almost 1-year experience. She has knowledge of languages like C, C++, Java and Scala. She is familiar with Object-Oriented Programming Paradigms and also has an interest in relational database technologies. Her hobbies include travelling, reading novels and listening to music.