[scala] How to model type-safe enum types?

2 Answers

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

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?

A slightly less verbose way of declaring named enumerations:

object WeekDay extends Enumeration("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat") {
  type WeekDay = Value
  val Sun, Mon, Tue, Wed, Thu, Fri, Sat = Value

WeekDay.valueOf("Wed") // returns Some(Wed)
WeekDay.Fri.toString   // returns Fri

Of course the problem here is that you will need to keep the ordering of the names and vals in sync which is easier to do if name and val are declared on the same line.

just discovered enumeratum. it's pretty amazing and equally amazing it's not more well known!



scala scala   enums