Exhaustive Matching
Compiler-checked completeness.
What Is Exhaustive Matching?
A match is exhaustive when it handles every possible value of the type being matched.
For a sealed trait, the compiler knows all variants and can check that your match covers them all.
A Complete Match
When you handle every variant of a sealed trait, the compiler is satisfied and no warning appears.
sealed trait Color
case object Red extends Color
case object Green extends Color
case object Blue extends Color
object Main {
def name(c: Color): String = c match {
case Red => "red"
case Green => "green"
case Blue => "blue"
}
def main(args: Array[String]): Unit = {
println(name(Blue))
}
}All lessons in this course
- Case Classes
- Sealed Traits
- Algebraic Data Types
- Exhaustive Matching