How to model type-safe enum types?

Jesper picture Jesper · Aug 24, 2009 · Viewed 105k times · Source

Scala doesn't have type-safe enums like Java has. Given a set of related constants, what would be the best way in Scala to represent those constants?

Answer

oxbow_lakes picture oxbow_lakes · Aug 24, 2009

I must say that the example copied out of the Scala documentation by skaffman above is of limited utility in practice (you might as well use case objects).

In order to get something most closely resembling a Java Enum (i.e. with sensible toString and valueOf methods -- perhaps you are persisting the enum values to a database) you need to modify it a bit. If you had used skaffman's code:

WeekDay.valueOf("Sun") //returns None
WeekDay.Tue.toString   //returns Weekday(2)

Whereas using the following declaration:

object WeekDay extends Enumeration {
  type WeekDay = Value
  val Mon = Value("Mon")
  val Tue = Value("Tue") 
  ... etc
}

You get more sensible results:

WeekDay.valueOf("Sun") //returns Some(Sun)
WeekDay.Tue.toString   //returns Tue