tags:

views:

48

answers:

1

How to manually specify an integer value bound to a particular enumeration value in Scala?

+1  A: 

Like this? Not quite sure what you are asking.

object WeekDay extends Enumeration {
  type WeekDay = Value
  val Mon, Tue, Wed, Thu, Fri, Sat, Sun = Value
}

import WeekDay._
def idToWeekDay(id: Int): Option[WeekDay] = WeekDay.iterator.find(_.id == id)

println(idToWeekDay(2))

Prints "Some(Wed)"

Eric Bowman - abstracto -
I supposed enumeration values have a digital synonym and can be casted to Int, like in other languages like C# or C++. Seems that in Scala they haven't. So I've just defined my own toInt method in the enum value class now.
Ivan
enumVal.id doesn't do what you want? That's how you *extract* the integer value from an enum. My code allows you to *specify* an integer value, and get the corresponding enum. Presumably you want to do one or the other?
Eric Bowman - abstracto -