← Back to Scala Course | Chapter 10: Pattern Matching | Lesson 3 of 7

Matching Tuples

In this page:

  1. Matching Tuples

Matching Tuples

A pattern like case (a, b) => destructures a tuple directly into its component parts inside a match branch, binding each part to a new variable. This works for tuples of any size and can be combined with type or literal patterns on individual components. It's a much more direct way to work with tuple contents than repeatedly calling ._1, ._2.

Note: Tuple patterns can mix literal values and variable bindings, like case (0, y) => ... to match only when the first element is exactly 0.

Example: Matching Tuples

markup
object Main extends App {
  val point = (3, 4)

  val description = point match {
    case (0, 0) => "origin"
    case (x, 0) => s"on the x-axis at $x"
    case (0, y) => s"on the y-axis at $y"
    case (x, y) => s"at ($x, $y)"
  }

  println(description)
}
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.