Scala pattern matching for case class

We learned about pattern matching in the past and there were a lot of “we will learn about this later“.

Some of the later is today !

One of the big advantage of case class over class is the built-in support for pattern matching. We are going to see the same advantage with case object in a later SKB.

Coming back to case class. You can perform several test using pattern matching:

  • Extraction of field: case Person(firstName, lastName) => ???
  • Extraction of field with condition: case Person(firstName, lastName) if firstName.startsWith("L") => ???
  • Filter with exact match: case Person("Leo", lastName) => ???
  • Filter with exact match and handle on case class: case p @ Person("Leo", lastName) => ???
  • Several filters: case p @ (Person("a", _) | Person(_, "b")) => ???
Reveal more information and clues
Load Exercise