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 sensible toString
and valueOf
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:
WeekDay.valueOf("Sun") //returns None
WeekDay.Tue.toString //returns Weekday(2)
Whereas using the following declaration:
object WeekDay extends Enumeration {
type WeekDay = Value
val Mon = Value("Mon")
val Tue = Value("Tue")
... etc
}
You get more sensible results:
WeekDay.valueOf("Sun") //returns Some(Sun)
WeekDay.Tue.toString //returns Tue