Scala – Enumeratum

Enumeratum is a third party enumeration library for Scala. It is also probably the most used enumeration library amongst all scala developers. It is also quite similar to Scala enumerations so using it is quite easy. To start using enumeratum, it needs to be imported into the Scala project. In the build.sbt add the following. See Below

val enumeratumVersion = "1.5.13"

libraryDependencies ++= Seq("com.beachape" %% "enumeratum" %
  enumeratumVersion
  )

Using enumeratum is pretty simple. See Below

import enumeratum._
object test extends App {
  sealed trait Color extends EnumEntry

  object Color extends Enum[Color]{
    val values = findValues

    case object Red extends Color
    case object Blue extends Color
    case object Green extends Color
    case object Purple extends Color
  }
}

Let’s go thru the code line by line

  1. The first line to look at is the import enumeratum._ which is pretty self-explanatory.
  2. The next line sealed trait Color extends EnumEntry creates a sealed trait called Color which extends an enumeratum trait called EnumEntry.
  3. findValues is a protected method which invokes a macro
  4. Finally, we have our Enum values.

Enumeratum provides methods similar to Scala enumerations library for checking index, retrieving a list of values.

sealed trait Color extends EnumEntry

object Color extends Enum[Color]{
//Use
  val values = findValues

  case object Red extends Color
  case object Blue extends Color
  case object Green extends Color
  case object Purple extends Color
}
//Prints the index of the enum value Red
println(Color.indexOf(Color.Red))

//Prints a List of all the enums
println(Color.values.toList)

//Prints Red
println(Color.Red)

Additional attributes can be added to the enumerations using enumeratum. See Below

sealed abstract class Color(val desc:String, val colorID: Int) extends EnumEntry

object Color extends Enum[Color]{
  val values = findValues
  case object Red extends Color("I am Red", 100)
  case object Blue extends Color("I am Blue", 200)
  case object Green extends Color("I am Green", 300)
}
//Prints - I am Red
println(Color.Red.desc)

//Prints - 100
println(Color.Red.Id)

Pattern matching is exhaustive in the case of enumeratum and if checks are not exhaustive a Warning is shown during compile time. Refer to the match-case example in scala enumeration or case objects entry.

Enumeratum provides numerous integrations and for a detailed read I would suggest going to this link.

Hopefully, you have now got the basics of Scala enumerations and the variants available in the language. I hope this has been helpful.

Till next time!

Leave a Comment