TExcelTAD
Home › Scala › Scala Tuples

Scala Tuples

A tuple groups a fixed number of values, possibly of different types, into one value — without declaring a class. Tuples are perfect for returning two or three results from a method or for temporary pairs like a key and a value.

Creating tuples

scala · try it yourself
@main def run(): Unit =
  val point = (3, 4)
  val person = ("Noor", 28, true)
  val pair = "x" -> 42           // a 2-tuple, too
  println(point)
  println(person)
  println(pair)
  val typed: (String, Int, Boolean) = person
  println(typed)
(3,4)
(Noor,28,true)
(x,42)
(Noor,28,true)

The type of ("Noor", 28, true) is (String, Int, Boolean) — each position keeps its own type.

Accessing elements

You can read elements by position with _1, _2, … or, in Scala 3, with a zero-based index like t(0). Most often you destructure the tuple into named values.

scala · try it yourself
@main def run(): Unit =
  val book = ("Dune", "Herbert", 1965)
  println(book._1)
  println(book._3)
  println(book(1))

  val (title, author, year) = book
  println(s"$title by $author ($year)")
  println(book.size)
  println(book.toList)
Dune
1965
Herbert
Dune by Herbert (1965)
3
List(Dune, Herbert, 1965)

Tip: Destructuring with meaningful names is much easier to read than _1 and _2. If you find yourself passing the same tuple shape around a lot, turn it into a case class.

Returning several values

scala · try it yourself
def stats(xs: List[Double]): (Double, Double, Double) =
  val mean = xs.sum / xs.size
  (xs.min, xs.max, mean)

def divMod(a: Int, b: Int): (Int, Int) = (a / b, a % b)

@main def run(): Unit =
  val (lo, hi, avg) = stats(List(4.0, 8.0, 15.0, 1.0))
  println(s"min=$lo max=$hi mean=$avg")
  val (q, r) = divMod(17, 5)
  println(s"17 = 5 * $q + $r")
min=1.0 max=15.0 mean=7.0
17 = 5 * 3 + 2

Tuples in collections

Many collection methods produce tuples: zip, zipWithIndex, partition, span and iterating over a Map.

scala · try it yourself
@main def run(): Unit =
  val names = List("ann", "bo", "cid")
  val ages = List(31, 25, 40)
  val people = names.zip(ages)
  println(people)
  for (name, age) <- people if age > 30 do println(s"$name is over 30")
  println(people.map((n, a) => s"$n:$a"))
  val (young, old) = people.partition(_._2 < 30)
  println(young)
  println(people.unzip)
List((ann,31), (bo,25), (cid,40))
ann is over 30
cid is over 30
List(ann:31, bo:25, cid:40)
List((bo,25))
(List(ann, bo, cid),List(31, 25, 40))

In Scala 3 a lambda with two parameters like (n, a) => … is automatically applied to a 2-tuple — no case needed.

Pattern matching on tuples

scala · try it yourself
def compare(a: Int, b: Int): String = (a.compare(b), a % 2 == 0) match
  case (0, _)     => "equal"
  case (1, true)  => s"$a is bigger and even"
  case (1, false) => s"$a is bigger and odd"
  case _          => s"$b is bigger"

@main def run(): Unit =
  println(compare(4, 4))
  println(compare(8, 3))
  println(compare(9, 3))
  println(compare(1, 3))
equal
8 is bigger and even
9 is bigger and odd
3 is bigger

Tuple operations in Scala 3

Scala 3 treats tuples almost like lists of types, so you can add elements and concatenate tuples:

scala · try it yourself
@main def run(): Unit =
  val t = (1, "two")
  val longer = t :* 3.0
  val front = "zero" *: t
  val joined = t ++ (true, 'x')
  println(longer)
  println(front)
  println(joined)
  println(joined.size)
(1,two,3.0)
(zero,1,two)
(1,two,true,x)
4

Tuple or case class?

Use a tuple when… Use a case class when…
the grouping is short-lived (inside a method) the data is part of your domain model
positions are obvious ((key, value)) fields need names to be understood
there are 2–3 elements there are many fields, or you need methods

Test yourself

What is the type of ("a", 1)?

  1. List[Any]
  2. (String, Int)
  3. Map[String, Int]
  4. Array[Any]

Given val t = (10, 20, 30), what is t._2?

  1. 10
  2. 20
  3. 30
  4. A compile error

What does List(1, 2).zip(List("a", "b")) produce?

  1. List(1, 2, a, b)
  2. List((1,a), (2,b))
  3. Map(1 -> a, 2 -> b)
  4. (List(1, 2), List(a, b))