Enumerations represent meaningful descriptions for more primitive data types. Scala Enumeration trait can be used to define a finite set of values. Let’s see a simple declaration and understand what it all means
- The first line is extending the Enumeration trait
- The second line is a declaration of type alias so that it makes the code a bit more meaningful instead of just saying Value – for example declaring a function
- In the third line – at the end, it says Value, which is a method and not the type Value mentioned in the second line. This method returns a type Value.
- Each element of an enum has a unique running id, which is auto-incremented automatically at the time of assignment.
Specific values can also be assigned the elements in scala enumerations. See Below
Enumerations can be passed to functions. However, there are a couple of issues, if values other than the ones in the match case are passed to the functions.
- Scala compiler does not raise any error during code compilation.
- The program throws a match exception during run-time.
Makes one wonder – “This does not feel right”. As Scala developer, you would expect an error/warning at compile time for a non-exhaustive check.
type Colors = Value
val Red = Value("Red")
val Blue = Value("Blue")
val Green = Value("Green")
val Yellow = Value("Yellow")
}
//No warnings. No exhaustive check. Compiles ok.
def findColor(c: Colors.Value):String = {
c match {
case Red: "Found Red"
}
}
val blue = Colors.withName("Blue")
//Generates a match exceptionm because enum "Blue" is
//not in the match case
println(findColor(c))
This limitation of the enumerations can be overcome by using case objects. Check out the entry on case objects.