Enums in Scala

[To cut to the chase, there is a link to a Scala Enum class you might find useful at the end of this post.]

Newcomers to Scala are often surprised to find that it is easier to write enums in Java than it is in Scala. Nearly everything else is easier in Scala than in Java, and often has preferable semantics as well, so the fact that enums are easier in Java comes as a bit of a shock.

But once you think about it, it makes some sense. The designers of Scala resist putting in highly focused language features, instead preferring features that have very broad applicability. The designers of Java said “Developers need enums; let’s enhance the language to make it easy to get good enums.” The designers of Scala, on the other hand, want as much as possible for problems to be solved by writing classes and traits and putting them in a library. The Scala language designers ask themselves questions like “Developers need to be able to do things like X and Y; have we made it possible to write good library solutions for such things?” Something that is preventing library designers from creating good solutions to common problems is a good argument for a new language feature. The Scala language designers tend to see their role at a different level of abstraction.

Consider Perl’s terse syntax for hash tables. The Perl designers (i.e. Larry Wall) decided to build in language features to make hash tables easy to create and use, whereas the Java designers decided to do that in a library rather than in the language itself.

In the same way, Java targeted enums directly, and as a result the syntax is fairly minimal, whereas the Scala folks have so far decided that the problem doesn’t warrant new language features. And even if the Scala folks were to do something special for enums, they couldn’t make it three times easier to create an enum than in Java; it would be about the same.

It could certainly be easier, but without too much difficulty you can make enums in Scala that are similar to Java enums, and actually do a little more. There seems to be a lot of churn on the web about how to do enums well in Scala, so I wrote up something about my own implementation in this StackOverflow answer (how did developers get anything done before StackOverflow?).

UPDATE:  Wouldn’t macros (available in 2.10) allow for a very usable enum facility?  I wouldn’t be surprised to see something in 2.11.  Ah — here’s a thread about that.  And another.

[other Scala posts]

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: