Scala 3 Enum vs Enumerations

Whats the difference between a scala Enum vs a scala Enumeration?

Also, I could find Enumeration in the scala 3 ref (Enumeration)

but I couldnt find Enum: does anyone have a link?

Enumeration exists since Scala 2 and it’s a mistake, never ever use it.

enum is a keyword added in Scala 3 that is just sugar syntax for a common pattern in Scala 2 to define ADTs (and thus enums) using sealed traits and case classes / objects

3 Likes



The above are from Scala 3 by Example - Algebraic Data Types for Domain Driven Design - …

3 Likes

Thanks for this clear advice!

1 Like

To clarify: It’s not just that, it also generates Java-compatible Enums, which is handy working with java-libs.

Here’s some background on Scala’s Enumeration: enums - Using Enumerations in Scala Best Practices - Stack Overflow

Uhm my definition of sugar syntax is that it just generates different code than what you see.
Making them Java enums is just a matter of extending an interface IIRC.

Unless your point was that I missed mentioning that. Which then fair, thanks for the addition.
I just don’t consider that to be a good feature either but that is another discussion.

IIUC you can’t write a real java compatible enum in “regular” scala code. At the very least because there needs to be a special flag enabled in the class file, but possibly it also requires other inexpressible constructs. So in that sense it is more than syntax sugar.

Uhm is that so? My understanding was that all you needed was to extend an interface but I may be wrong in that.
If so, yeah is more than syntax.

Although, again, I don’t think it doing that by default is a good feature.

This is a scary diagnostic:

An exception has occurred in the compiler (21.0.2). Please file a bug against the Java compiler via the Java bug reporting page (https://bugreport.java.com) after checking the Bug Database (https://bugs.java.com) for duplicates. Include your program, the following diagnostic, and the parameters passed to the Java compiler in your report. Thank you.
com.sun.tools.javac.code.Symbol$CompletionFailure: class file for scala.reflect.Enum not found

but putting it on the class path works.

-cp ".sdkman/candidates/scala/3.4.0/lib/*"

I needed this exercise in recalling Java syntax.

public class Colorized {
        public Color test(Color c) {
                switch (c) {
                        case Red: return Color.Green;
                        default: return Color.Blue;
                }
        }
}

where

enum Color extends Enum[Color]:
  case Red, Green, Blue

I’m not motivated to try advanced features, but javap says ACC_ENUM everywhere.

Also Scala 3: Enum vs Enumerations is my favorite monster movie sequel.

It’s the rare monster movie where instead of Tokyo they devastate the shores of Lake Geneva.

Here’s a short demonstration of Scala 3 Enum Java interop (towards the end of the video): https://www.youtube.com/watch?v=YlVVhLvN71Y