match Expressions, Part 2 (Scala 3 Video)
This lesson looks at more advanced uses of Scala match
expressions.
Matching multiple patterns on one line
Match multiple patterns on one line (in one case
):
def isTrue(a: Matchable): Boolean = a match // VERSION 2
case 0 | "" | "0" | false => false
case _ => true
// another example of multiple patterns
i match
case 1 | 3 | 5 | 7 | 9 => "odd"
case 2 | 4 | 6 | 8 | 10 => "even"
case _ => "other"
Giving the default case a variable name
How to give the default catch-all case a name:
i match
case 1 | 3 | 5 | 7 | 9 => "odd"
case 2 | 4 | 6 | 8 | 10 => "even"
case default => s"You gave me a $default"
Using case classes in match expressions
case
classes and match
expressions:
// A function that takes `SentientBeing`
// How to extract info from `case` classes
// The cases are exhaustive because of the sealed traits
sealed trait SentientBeing
sealed trait Animal extends SentientBeing
case class Dog(name: String) extends Animal
case class Person(name: String, age: Int) extends SentientBeing
// later in the code ...
def getInfo(sb: SentientBeing): String = sb match
case Person(name, age) =>
s"Person, name = $name, age = $age"
case Dog(name) =>
s"Dog, name = $name"
Using a match expression as the body of a function
Using a match
expression as the body of a function, in this case a recursive function:
// recursive (but not tail-recursive)
def sum(list: List[Int]): Int = list match
case Nil => 0
case head :: tail => head + sum(tail)
// same example, but with added debug comments
def sum(xs: List[Int]): Int = xs match
case Nil =>
println("Nil")
0
case head :: tail =>
println(s"head = $head, tail = $tail")
head + sum(tail)
Using match with Option/Some/None
Using with Option/Some/None
:
val allow: Boolean = ageAsOption match
case Some(i) => i >= 21
case None => false
More reading
Update: All of my new videos are now on
LearnScala.dev