Sealed Traits in Scala

You probably know the idea behind using case classes and pattern matching them. Sometimes you might want the help of the compiler to tell you if you have pattern matched correctly by covering all possible cases. You can now get this sort of compiler support by creating a superclass for the case classes and marking them as sealed.

 1sealed trait Person
 2case class Student(name: String) extends Person
 3case class Teacher(name: String) extends Person
 4case class Author(name: String) extends Person
 5case class Bertender(name: String) extends Person
 6...
 7...
 8def printAPerson(person: Person) = person match {
 9  case p @@ Student(_) => println(p)
10  case p @@ Teacher(_) => println(p)
11}

With the code above, the compiler would now tell us that the match is not exhaustive and would show us the following:

1warning: match may not be exhaustive.
2It would fail on the following inputs: Author(_), Bertender(_)
3def printAPerson(person: Person) = person match {...}

Sealed traits or abstract classes is a guarantee for the compiler to know that all the classes that implement the sealed trait or sealed abstract class should be declared in the same file. This way, the compiler knows for sure that all the possible subclasses is in the same file and can therefore provide us with the warning message on our pattern match logic.

Now it's time for you to go figure out the meaning of the following code snippet:

1def printAPerson(person: Person) = (person: @@unchecked) match {
2  case p @@ Student(_) => println(p)
3  case p @@ Teacher(_) => println(p)
4}