What is a sealed trait?

John Threepwood picture John Threepwood · Jun 26, 2012 · Viewed 87.6k times · Source

Sealed classes are described in 'Programming in Scala', but sealed traits are not. Where can I find more information about a sealed trait?

I would like to know, if a sealed trait is the same as a sealed class? Or, if not, what are the differences? When is it a good idea to use a sealed trait (and when not)?

Answer

paradigmatic picture paradigmatic · Jun 26, 2012

A sealed trait can be extended only in the same file as its declaration.

They are often used to provide an alternative to enums. Since they can be only extended in a single file, the compiler knows every possible subtypes and can reason about it.

For instance with the declaration:

sealed trait Answer
case object Yes extends Answer
case object No extends Answer

The compiler will emit a warning if a match is not exhaustive:

scala> val x: Answer = Yes
x: Answer = Yes

scala> x match {
     |   case No => println("No")
     | }
<console>:12: warning: match is not exhaustive!
missing combination            Yes

So you should use sealed traits (or sealed abstract class) if the number of possible subtypes is finite and known in advance. For more examples you can have a look at list and option implementations.