🎓 A1Learner
🔍
0 of 50 lessons completed

Scala Tuples

A tuple is a small collection that groups values together in a fixed order. Unlike a list, a tuple can hold values of different types at the same time.

Fields read the values inside a tuple

A tuple is written with round brackets and commas. The fields ._1 and ._2 read the values by their position.

@main def main(): Unit =
  val pair = ("Ana", 90)
  println(pair._1)
  println(pair._2)

Splitting gives each value its own name

One line can split a tuple into separate values. After the split, each name can be used on its own.

@main def main(): Unit =
  val pair = ("Bo", 75)
  val (name, score) = pair
  println(name)
  println(score)

A tuple can hold three values

Tuples are not limited to two values. The third value here is read with the field ._3.

@main def main(): Unit =
  val color = ("red", 255, 0)
  println(color._1)
  println(color._2)
  println(color._3)

Example

@main def main(): Unit =
  val results = List(("Ana", 90), ("Bo", 75), ("Cy", 88))
  for pair <- results do
    println(s"${pair._1}: ${pair._2}")

Key points

  • Grouping: ("Ana", 90) creates a tuple that groups a name and a score together.
  • Types: The values inside one tuple can have different types.
  • First field: pair._1 gives the first value in the tuple.
  • Second field: pair._2 gives the second value in the tuple.
  • Splitting: val (name, score) = pair gives each value in the tuple its own name.
  • Bigger tuples: A tuple can hold three values, and the third value is read with ._3.

In this example, the program creates a list where each item is a tuple holding a name and a score. A for loop visits each tuple in order and prints its two fields as one line of text.

Note

A list can hold tuples, so pairs of related values can be stored together in one list.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Scastie

Exercise

A program creates val pair = ("Bo", 75). What does pair._2 give?