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:
Syntax
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
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)
}
Login to try C/C++/Java/PHP code in the editor
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
- Matching a tuple against a pattern of the wrong size, such as
case (a, b, c)on a 2-tuple, which fails to compile. - Using a variable name that starts with a capital letter in a pattern, as in
case (X, 0), where Scala treatsXas a constant to compare against. - Forgetting that
case (x, 0)only matches when the second element equals0.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: