Tuples
A tuple groups a fixed number of values of different types into one value, without a class and without names for the positions. (3, 4) is a pair of Int, ("temperature", 21.5) is a String and a Double, and the compiler knows the type of every position, which a list cannot say.
A pair and its positions
A tuple literal is written in parentheses with a comma. The arrow form key -> value builds the same pair and reads better where the pair is a map entry. The positions are called _1, _2 and so on, and a val pattern takes the pair apart in one line:
pairs.scala
@main def pairs(): Unit =
val point = (3, 4)
println(point)
println(point._1 + point._2)
println(point.swap)
val (x, y) = point
println(s"x = $x, y = $y")
val labelled = "temperature" -> 21.5
println(labelled)
println(labelled._2)
println((1, "one") == (1, "one"))
scala-cli run --server=false pairs.scala
(3,4)
7
(4,3)
x = 3, y = 4
(temperature,21.5)
21.5
true
The tuple prints its values in the order they were written, and swap is the one method every pair has. A pair is a Tuple2, a triple a Tuple3, and two tuples of equal values are equal, which is the == of a case class. The syntax key -> value is a method like any other, so a pair is the natural entry of a Map and needs no wrapper class.
A tuple as a result
A method with two things to return returns a tuple rather than a class that exists for one call. minMax is the smallest example: the caller takes the two values apart at the call site, and a triple shows a tuple of three different types:
returned.scala
def minMax(values: List[Int]): (Int, Int) =
(values.min, values.max)
@main def returned(): Unit =
val bounds = minMax(List(4, 9, 2, 7))
println(bounds)
println(bounds._1)
val triple = (1, "two", 3.0)
println(triple._3)
println(triple.productArity)
println(triple.toList)
val nested = (1, ("a", true))
println(nested._2._2)
scala-cli run --server=false returned.scala
(2,9)
2
3.0
3
List(1, two, 3.0)
true
The type (Int, Int) is Tuple2[Int, Int], and productArity is the number of positions. A tuple nests, and toList turns its values into a list of their common supertype here. Once a tuple travels further than one method, a case class with named fields is the better type: a reader of _1 has to remember what it holds, and nothing checks that memory.
Related
- Case classes: a tuple with names for its positions.
- Methods and parameters: the result type of minMax.
- Operators are methods: the -> that builds a pair is one.
- Java: has no tuple type, which is why a Java method with two results needs a class.
Article author: Arthur Isaev