Last modified on 4 November 2012, at 23:41

Scala/Tuples

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

val idUsername = (0, "randomusername")
println("Id is: " + idUsername._1) //Prints "Id is: 0".
println("Username is: " + idUsername._2) //Prints "Username is: randomusername".

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:

val (id, username) = (0, "randomusername")
println("Id is: " + id) //Prints "Id is: 0".
println("Username is: " + username) //Prints "Username is: randomusername".

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:

def getSumAverage(numbers:List[Int]) = {
  val sum = numbers.sum
  val average = (sum:Double) / numbers.length
  (sum, average)
}
val numbers = List(1, 2, 30, 45, 13)
val (sum, average) = getSumAverage(numbers)
println("Sum, average is: " + sum + ", " + average) //Prints "Sum, average is: 91, 18.2".

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:

val (number, weight, name) = (7, 1.05, "Apple")
val (x, y, z, tempature) = (30.0, 100.0, -10.0, -5.3)