Sealed traits

A trait can be sealed, meaning it can be extended only in the same file in which it is declared. Sealed traits are useful as the compiler can do exhaustiveness checks. What does being exhaustive mean? It is pretty simple. Try out the following example to know more:

scala> def m(n : Int) = n < 10
m: (n: Int)Boolean
scala> :t m _
Int => Boolean
scala> m(9) match {
     |   case true => println(""True"")
     | }
<console>:12: warning: match may not be exhaustive.
It would fail on the following input: false
       m(9) match {
        ^
True

The compiler can reason about the pattern match. It knows that the return type of m is Boolean. Note that we are calling the method and matching the result against true. What if the method returns false? This is the reason ...

Get Scala Functional Programming Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.