What's a Tuple?
A tuple is a comma-separated list of different data types (such as String, Int, Bool) represented as a single value by enclosing those values in parenthesis.
This is what a simple tuple looks like.
The first parameter represents the name, the second parameter represents the age and the third, lets say, whether the employee is married or not.
Lets try and print the employee variable
Compiler interpreted the value of employee and gave us the list of data types that it includes order-wise.
To print the name and age of employee we simply need to write
Named parameters in Tuples
As you might have guessed, accessing the employee through indexes is not very appealing as it might create a lot of confusion as to which parameter serves what purpose. To make tuple more readable we have an option to give name to the parameters.
Let's rewrite the employee, this time in a much more expressible form.
And when we try to print the values
This has better readability when compared to what we had initially.
Tuple sounds similar to an Array, why not just use the good old Array instead?
Tuple and Array have similar functionality and you can almost use an array everywhere where you have a Tuple. Below are the reasons and possible scenarios to help you decide when to use a Tuple instead of an Array -
- Fixed number of parameters: In a Tuple, you need to pass the exact number of parameters no more no less. For example, in employee Tuple above, to create a valid Tuple you need to pass name, age, and marital status. So at the time of accessing a Tuple, you can be sure of the values you are going to get. Whereas, in an array, you will have to perform a check for the existence of each parameter by traversing through the indexes.
- Easy access with named parameters: It's really easy to access a tuple which has named parameters. You can use the dot notation to directly access the parameter you want without having to go through each element of the array.
- Numer of elements are known beforehand: There might a case where you already know the number of parameters which are required. For example, let's say there is a function which returns the first name and last name of a person. In this case, we are sure that the function will return only two String objects. Using an Array in such a case might be an overkill and probably a waste of time.
Tuple can come handy in a lot of situations and is a better alternative to an Array when the size of array is going to be fixed and relatively small. Once you get familiar with it, it's hard not to use Tuple in your day to day life.
Have something to add on? Spotted a mistake? Please feel free to comment down below.