Reputation: 39
How can I define an enum with specific numeric values in Scala and be able to get the value list from the type?
If I define the enum using the Enumeration
type as follows:
object MyEnum extends Enumeration {
type MyEnum = Value
val A: Byte = -10
val B: Byte = 0
val C: Byte = 10
}
and try to get the values as follows:
val byteValues = MyEnum.values.toList.map(_.id.toByte)
then I get an empty sequence.
Upvotes: 0
Views: 689
Reputation: 27356
You can give a parameter to the Value
method to set the enumeration to a specific value. Subsequent calls to Value
without a parameter will generate the next integer in the sequence
object MyEnum extends Enumeration {
val A = Value(-1)
val B, C = Value
}
It should be obvious how to use my answer to solve the updated question, but here is the code, just in case
object MyEnum extends Enumeration {
val A = Value(-10)
val B = Value(0)
val C = Value(10)
}
Upvotes: 1
Reputation: 39
The correct way to define the enum is:
object MyEnum extends Enumeration {
type MyEnum = Value
val A = Value(-10)
val B = Value(0)
val C = Value(10)
}
then getting the values works.
Upvotes: 2