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

Matching Case Classes

In this page:

  1. Matching Case Classes

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)
}
🔒

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.