Scala Enumerations
Introduction to Scala enumerations
Enumerations can be very useful when we want to create discrete set of items. Often these items help us to differentiate a run time instances having the same base class. Scala provides an Enumeration helper class that we can use to create enumerations[1].
Scala does not have enumerated types [1]. In contrast, it provides the Enumeration helper class to help us create enumerations. This is shown in the code snippet below
object Element extends Enumeration{
val QUAD, TRI, HEX, TET = Value
}
Above we defined an enumerated type with four fields. The above initialization is equivalent to [1]
...
val QUAD = Value
val TRI = Value
val HEX = Value
val TET = Value
...
println(Element.QUAD)
println(Element.TRI)
Each call to the Value method returns a new instance of an inner class, also called Value [1]. We can also initialize the enumeration fields with ids, names or both as shown below
object Element_2 extends Enumeration{
val QUAD = Value(0, "QUAD")
val TRI = Value(1, "TRI3")
}
println(Element_2.QUAD)
println(Element_2.TRI)
If not specified, the id is one more than the previously assigned one, starting with zero and the default name is the field name [1].
Note that the type of the enumeration is Element.Value and not just
Element. The latter is just the type of the object holding the values. We can use aliases to disambiguate this [1]
object Element_3 extends Enumeration{
type Element_3 = Value
val QUAD = Value(0, "QUAD")
val TRI = Value(1, "TRI3")
}
Now the type of the enumeration is Element_3.Element_3 [1].
for( e <- Element_3.values) println(e.id + ":" + e)
Finally, you can look up an enumeration value by its id or name [1]. Both of the
following yield the object Element.HEX :
println(Element(2))
println(Element.withName("HEX"))
- Cay Horstmann,
Scala for the Impatient 1st Edition