0

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.

Danny Varod
  • 17,324
  • 5
  • 69
  • 111
zozo
  • 39
  • 2

2 Answers2

2

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.

zozo
  • 39
  • 2
  • 2
    Note that the `type` declaration is not necessary, it will work without it. – Tim Mar 19 '19 at 12:01
  • @Tim, true but then you'd have to use MyEnum.Value everywhere you declare a variable instead of just using MyEnum. See [this answer](https://stackoverflow.com/a/11067507/38368) for more info on this. – Danny Varod Sep 12 '19 at 12:03
1

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
}

Update following change to question

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)
}
Tim
  • 26,753
  • 2
  • 16
  • 29
  • 1
    My question was about specific numeric values, not necessarily sequential. I'll change my question to clarify. – zozo Mar 19 '19 at 11:43