O'Reilly logo

Scala Functional Programming Patterns by Atul S. Khot

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required