We are going to learn about pattern matching today. 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 use pattern matching is match
. But as you saw, you can also use it inside map
, as well as flatMap
and filter
and more.
The overall syntax is:
And similar inside avalue match {
case holder => action
case _ => default case
}
map
or other:list.map {
case holder => action
case _ => default case
}
It works kind of like a switch
in other languages. And similar to switch
, the case
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 that pattern matching can be used and we only saw a few here, let's review:
case n => ???
case _ => ???
case n if n % 2 == 0 => ???
case 3 => ???
or case "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) => ???