I think it depends on what you're going to be doing. A sealed trait helps more at compile time, but Enumeration
helps more at runtime.
The big thing about sealed traits is that you get a compiler warning for non-exhaustive matches.
sealed trait Animal
object Cat extends Animal
object Dog extends Animal
def foo(a: Animal) = a match {
case Cat => "cat"
}
.
Warning:(7, 26) match may not be exhaustive.
It would fail on the following input: Dog
def foo(a: Animal) = a match {
^
In the corresponding Enumeration
version, you don't have that, so this mistake compiles without warning:
object Animal extends Enumeration {
type Animal = Value
val Cat, Dog = Value
}
import Animal._
(Dog: Animal) match {
case Cat => "cat"
}
But, of course, just by looking at the API, you know there's some stuff that Enumeration
gives you for free. Enumeration
values have a String
name, there's a set of them that you can iterate over, and they have an ordering. If any of those things are important to you, then maybe that's what you need.
So if you're going to be pattern matching over the values, use a sealed trait. If you're going to be iterating over the values or looking them up by name, maybe use Enumeration
.
(Personally, I don't think I've ever had a reason to use Enumeration
, but YMMV.)