Richard Searle's Blog

Thoughts about software

Exhaustive Scala Enum

Posted by eggsearle on July 24, 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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: