Scala/Tuples

A tuple in Scala is an immutable sequence of values of multiple types. A simple example:

In the first line, we define a value named "idUsername", and assign it the value of a tuple with 2 values, also known as a pair. The tuple is defined by a matching pair of parenthesis, containing each element in sequence separated by commas. '0' is the first element and '"randomusername"' is the second element. In the second line, the first element of the tuple is accessed by calling the "_1" method on the value named "idUsername", and the value '0' is printed. In the third line, the second element of the tuple is accessed by calling the "_2" method on the value named "idUsername", and the value '"randomusername"' is printed.

Tuples support easy binding of elements to values:

In the first line, two identifiers are declared by using the keyword "val" followed by a pair of parenthesis, containing the identifiers separated by commas. This is followed by an equal sign, after which the tuple '(0, "randomusername")' is defined. The first identifier "id" is bound to the first element '0', while the second identifier "username" is bound to the second element '"randomusername"'. In the second line, the value named "id" is printed, giving "Id is: 0", and in the third line, the value named "username" is printed, giving "Username is: randomusername".

One of the uses of tuples is to return multiple values without having to create a class from scratch for that specific return:

In the first 5 lines, a function "getSumAverage" is defined, which takes a list of numbers, calculates the sum and the average of the given numbers, and returns the results as a tuple. In the sixth line, a list of numbers is defined and stored in a value named "numbers", and in the seventh line, the sum and average of those numbers is calculated and stored in the values "sum" and "average". In the final line, the sum and average is printed.

An example of a triple and a quadruple:

It is also worth noting that the numbers of binded elements should be exactly the number of TupleN, which means all of the below will generate an error:

Tuples in Scala, similar to Python, are usually used to store heterogeneous values. This means that It will make no assumptions on its elements types when it is transferred to other aggregative data structures such as List or Array.