Scala – Enumerations

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

object colors extends Enumeration{
  type colors = Value
  val Red, Blue, Green, Yellow = Value

//Prints Red

//Prints 0
  1. The first line is extending the Enumeration trait
  2. The second line is a declaration of type alias so that it makes the code a bit more meaningful instead of just saying Valuefor example declaring a function
  3. 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.
  4. 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

object colors extends Enumeration {
  type colors = Value
  val Red = Value("I am Red")
  val Blue = Value("I am Blue")
  val Green = Value("I am Green")
  val Yellow = Value("I am Yellow")

//Prints - I am Red

//Prints 0

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.

object Colors extends Enumeration{
  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

This limitation of the enumerations can be overcome by using case objects. Check out the entry on case objects.

Leave a Comment