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 a cautionary warning is issued.
If we include the false
clause, the warning would go away, as the code would never fail to match.
Let's take a look at another example in which we are matching against...