2

Is there a document that mentions explicitly whether a sealed trait with case objects is preferred vs Enumeration ? I personally have no real opinion/preference either way, but would like to be better informed as per best/recommended practice.

I did not find any existing SOF question on this, but if one exists with a solid answer please feel free to mark so here.

WestCoastProjects
  • 58,982
  • 91
  • 316
  • 560
  • possible duplicate of [Case classes vs Enumerations in Scala](http://stackoverflow.com/questions/1898932/case-classes-vs-enumerations-in-scala) – Chris Martin Sep 29 '14 at 05:29

1 Answers1

3

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

Chris Martin
  • 30,334
  • 10
  • 78
  • 137