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

Matching Case Classes

Matching case classes peeks inside an object and pulls out its fields as you check its kind. It is like opening a toy box and reading the labels on each item.

In this page:

  1. Matching Case Classes
Syntax
scala
value match {
  case ClassName(field1, field2) => expression
  case OtherClass(field)          => expression
}

Matching Case Classes

Case classes support pattern matching directly on their fields, like case Point(x, y) =>, destructuring an instance into its constructor parameters within the branch, without calling ._1-style accessors.

This works because case classes automatically generate an unapply method that pattern matching relies on behind the scenes. It's one of the biggest reasons case classes are preferred for data modeling in idiomatic Scala.

Note: Pattern matching on case classes relies on the automatically-generated unapply method -- this is exactly why case classes support it and plain classes don't, by default.

Example: Matching Case Classes

markup
case class Point(x: Int, y: Int)

object Main extends App {
  val p = Point(3, 4)

  val description = p match {
    case Point(0, 0) => "origin"
    case Point(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. Using a plain class instead of a case class and expecting case Point(x, y) to work, since a plain class has no unapply.
  2. Writing the wrong number of fields in the pattern, such as case Point(x) for a two-field class.
  3. Assuming pattern variables are var, when they are new val bindings only for that case.
🔒

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.