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
libraryDependencies ++= Seq("com.beachape" %% "enumeratum" %
enumeratumVersion
)
Using enumeratum is pretty simple. See Below
Let’s go thru the code line by line
- The first line to look at is the import enumeratum._ which is pretty self-explanatory.
- The next line sealed trait Color extends EnumEntry creates a sealed trait called Color which extends an enumeratum trait called EnumEntry.
- findValues is a protected method which invokes a macro
- Finally, we have our Enum values.
Enumeratum provides methods similar to Scala enumerations library for checking index, retrieving a list of values.
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
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!