Scala pattern matching

We are going to learn aboutpattern matchingtoday. At least, an introduction. Pattern matching is one of the key functionality of scala and it contributes to help you write clean and readable code.

The main keyword to usepattern matchingismatch. But as you saw, you can also use it insidemap, as well asflatMapandfilterand more.

The overall syntax is:

value match {

case holder => action

case _ => default case

}

And similar inside amapor other:

list.map {

case holder => action

case _ => default case

}

It works kind of like aswitchin other languages. And similar toswitch, thecaseare evaluated in order, the first one that evaluate to true will be executed and none of the other ones will be.

There are plenty of ways thatpattern matchingcan be used and we only saw a few here, let's review:

  • catch all:case n => ???
  • catch all without the value:case _ => ???
  • With condition:case n if n % 2 == 0 => ???
  • Exact match:case 3 => ???orcase "abc" => ???
  • List extraction:
    • Empty list:case Nil => ???
    • Extract head:case head :: tail => ???
    • One element:case head :: Nil => ???
    • Two elements:case first :: second :: Nil => ???
    • One element with condition:case head :: Nil if head % 2 == 0 => ???
    • Extract value:case 12 :: tail => ???
  • With types:case n: String => ???
  • Case classes: (there will be an SKB about it)
    • Extraction of field:case Person(firstName, lastName) => ???
    • Extraction of field with condition:case Person(firstName, lastName) if firstName.startsWith("L") => ???
    • Extraction of field with exact match:case Person("Leo", lastName) => ???
  • With regex: There will be an SKB about it
  • With Scala version of enumeration: There will be an SKB about it
I might have forgotten some. If so, please let me know in the comment below or on our discord server.

Reveal more information and clues
Load Exercise