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

Matching Tuples

Matching tuples opens a bundle and names its parts in one go, like unpacking a lunch tray into sandwich and juice. You can then act on each part.

In this page:

  1. Matching Tuples
Syntax
scala
tuple match {
  case (a, b) => expression
}

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)
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Matching a tuple against a pattern of the wrong size, such as case (a, b, c) on a 2-tuple, which fails to compile.
  2. Using a variable name that starts with a capital letter in a pattern, as in case (X, 0), where Scala treats X as a constant to compare against.
  3. Forgetting that case (x, 0) only matches when the second element equals 0.
🔒

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.