Are there any best-practice guidelines on when to use case classes (or case objects) vs extending Enumeration in Scala?
They seem to offer some of the same benefits.
Update March 2017: as commented by Anthony Accioly, the scala.Enumeration/enum
PR has been closed.
Dotty (next generation compiler for Scala) will take the lead, though dotty issue 1970 and Martin Odersky's PR 1958.
Note: there is now (August 2016, 6+ years later) a proposal to remove scala.Enumeration
: PR 5352
Deprecate
scala.Enumeration
, add@enum
annotationThe syntax
@enum
class Toggle {
ON
OFF
}
is a possible implementation example, intention is to also support ADTs that conform to certain restrictions (no nesting, recursion or varying constructor parameters), e. g.:
@enum
sealed trait Toggle
case object ON extends Toggle
case object OFF extends Toggle
Deprecates the unmitigated disaster that is
scala.Enumeration
.Advantages of @enum over scala.Enumeration:
- Actually works
- Java interop
- No erasure issues
- No confusing mini-DSL to learn when defining enumerations
Disadvantages: None.
This addresses the issue of not being able to have one codebase that supports Scala-JVM,
Scala.js
and Scala-Native (Java source code not supported onScala.js/Scala-Native
, Scala source code not able to define enums that are accepted by existing APIs on Scala-JVM).