I read an answer on SO where someone said that scala enumerations are useless, and you should just use java enumerations instead if you really need too.
Although I have used java enumerations before, I can't say I fully understand them as I don't code in java during my day job.
Can someone explain the differences between scala and java enumerations, and where exactly the shortcomings in scala enums are?
The main advantage of Scala's Enumeration is the regularity of the syntax.
If you want to add behavior to elements of your enum, just extend its
Val
class.Odersky likes them for their simplest use case as named int-valued constants. And he just promised on the mailing list, for the first time, that improved support is on the horizon.
But I recently used them to replace a list of strings, since the set of values is a bit set, nicer than a set of strings for look-up.
Instead of
or
Behavior:
ValueSet
is a bit set:Other stuff that seems to work in today's Scala:
It looks like Scala is not entirely friendly to Java enums:
The main weakness of Scala enums is the difficulty in adding methods and fields to them. In Java, it's trivial to use an enum as a Class with a fixed number of instances (which is, for example, why they're a good choice for implementing singletons).
In Scala however, Enums are just a set of possible values; adding methods and fields to them is a much more hacky process. So if you want anything beyond trivial behavior from the enum, Java enums are a much more convenient tool.
For example a Java enum might look like this:
However, in Scala, you would have to do this:
This doesn't look that bad in a trivial example like this, but it does add some confusing syntax, and adds the overhead of another class which will need to be implicitly converted to for most uses of the enum.
The main advantage I see to the Java enum is that you write exactly what you mean; an enum, with some methods and fields on it. In scala, you're writing something other than what you mean; you need to create an enum, which contains a class which has the methods and fields you want, and also defines a conversion from that class to the enum. It's a less idiomatic way to express the same idea.
As was pointed out in the comments, Scala does offer Case Classes, which can be used as an alternative to enums in many cases, and have a much cleaner syntax. But there still are some situations in which Case Classes aren't sufficient (such as when you want to iterate over all values), so regular enums still have their place. Correction: using macros does make it possible to iterate over Case Classes, but doing so has its own added complexity, while enums (in both Scala and Java) are much more straightforward to iterate over.