Crell / enum-comparison

A comparison of enumerations and similar features in different languages
80 stars 7 forks source link

Points about enumerations in Scala #24

Closed nafg closed 3 years ago

nafg commented 3 years ago

README.md says

I deliberately excluded languages with no native enum support. Languages such as Javascript, Go, or Ruby do not (as far as I can tell) have any native enumerations, although there are various hacky ways to simulate them in user space. That is not of interest to us at this time.

Scala 3, due to be released in a few months, will in fact have language support. http://dotty.epfl.ch/docs/reference/enums/enums.html

However Scala 2.x does not. Enumeration is a class in the standard library that uses reflection and takes advantage of several Scala language features to make it easy to define simple enumerations.

People often use sealed traits + case objects instead (which is basically how ADTs are done in Scala, and as linked above in Scala 3 enum/ADT support desugars to that.)

A popular approach is to use https://github.com/lloydmeta/enumeratum#usage, which uses Scala's compile-time metaprogramming vs. runtime reflection to provide enum support as a library.

Again, Scala 3 builds on that approach of using sealed trait + case objects / case classes, which is how ADTs are modeled as well, and provides first-class syntax for enums and ADTs. However enums can be compiled as java.lang.Enums.

So Scala really bridges your distinction of "Fancy Object" languages and "ADT" languages. ADTs are objects and classes that can be safely pattern matched. In Scala the syntax encourages you to think of classes as parameterized objects. And the new enum feature in Scala 3 generalizes over ADTs and enums. When some cases are parameterized you simply lose the capabilities that no longer make sense (like getting a list of all values) and keep everything else.

iluuu1994 commented 3 years ago

Thanks! The analysis is over and no longer our focus. We'll keep this in mind if we ever get back to it.