Richard Searle

home

Exhaustive Scala Enum

24 Jul 2011

This interesting post describes how to define an enum in Scala such that the compiler will flag a failure to exhaustively cover all the options. It also provides an implementation of values, which is often very useful. However, I found the gist did not function under either Scala 2.8.1 or 2.9.0-1. The compiler would falsely indicate that not all options were covered.  Using objects rather than vals resolved the problem. Arguably this is a clearer representation since Enum values are singletons.  It also avoids some of the "boilerplate" nature of the vals implementation, while retaining the compiler checking.
object Foos extends Enum {
  sealed trait EnumVal extends Value
  object F extends EnumVal { val name = "F" }
  object X extends EnumVal { val name = "X" }
}
Unfortunately, this implementation does not populate the values until each object is explicitly referenced.