Scala doesn't have type-safe enum
s like Java has. Given a set of related constants, what would be the best way in Scala to represent those constants?
相关问题
- Unusual use of the new keyword
- Get Runtime Type picked by implicit evidence
- What's the point of nonfinal singleton objects
- PlayFramework: how to transform each element of a
- Error in Scala Compiler: java.lang.AssertionError:
相关文章
- Gatling拓展插件开发,check(bodyString.saveAs("key"))怎么实现
- RDF libraries for Scala [closed]
- Why is my Dispatching on Actors scaled down in Akk
- How do you run cucumber with Scala 2.11 and sbt 0.
- Enum with associated value conforming to CaseItera
- Why do I have to cast enums to int in C#?
- GRPC: make high-throughput client in Java/Scala
- Setting up multiple test folders in a SBT project
Dotty (Scala 3) will have native enums supported. Check here and here.
I must say that the example copied out of the Scala documentation by skaffman above is of limited utility in practice (you might as well use
case object
s).In order to get something most closely resembling a Java
Enum
(i.e. with sensibletoString
andvalueOf
methods -- perhaps you are persisting the enum values to a database) you need to modify it a bit. If you had used skaffman's code:Whereas using the following declaration:
You get more sensible results:
After doing extensive research on all the options around "enumerations" in Scala, I posted a much more complete overview of this domain on another StackOverflow thread. It includes a solution to the "sealed trait + case object" pattern where I have solved the JVM class/object initialization ordering problem.
There are many ways of doing.
1) Use symbols. It won't give you any type safety, though, aside from not accepting non-symbols where a symbol is expected. I'm only mentioning it here for completeness. Here's an example of usage:
2) Using class
Enumeration
:or, if you need to serialize or display it:
This can be used like this:
Unfortunately, it doesn't ensure that all matches are accounted for. If I forgot to put Row or Column in the match, the Scala compiler wouldn't have warned me. So it gives me some type safety, but not as much as can be gained.
3) Case objects:
Now, if I leave out a case on a
match
, the compiler will warn me:It's used pretty much the same way, and doesn't even need an
import
:You might wonder, then, why ever use an Enumeration instead of case objects. As a matter of fact, case objects do have advantages many times, such as here. The Enumeration class, though, has many Collection methods, such as elements (iterator on Scala 2.8), which returns an Iterator, map, flatMap, filter, etc.
This answer is essentially a selected parts from this article in my blog.
just discovered enumeratum. it's pretty amazing and equally amazing it's not more well known!
You can use a sealed abstract class instead of the enumeration, for example: