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 asflatMap
andfilter
and more.
The overall syntax is:
value match { case holder => action case _ => default case }And similar inside a
map
or other:list.map { case holder => action case _ => default case }
It works kind of like aswitch
in other languages. And similar toswitch
, thecase
are 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:
case n => ???
case _ => ???
case n if n % 2 == 0 => ???
case 3 => ???
orcase "abc" => ???
case Nil => ???
case head :: tail => ???
case head :: Nil => ???
case first :: second :: Nil => ???
case head :: Nil if head % 2 == 0 => ???
case 12 :: tail => ???
case n: String => ???
case Person(firstName, lastName) => ???
case Person(firstName, lastName) if firstName.startsWith("L") => ???
case Person("Leo", lastName) => ???