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 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. Additional attributes can be added to the enumerations using enumeratum. See Below … Read more

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 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 … Read more

Scala – Case Objects

Case Objects are singleton objects similar to an object with the modifier case. Similar to case classes a lot of boilerplate code is added to when the object is prefixed with the modifer case. Case objects are also serializable as is the case with case classes which is really useful when you are using frameworks like Akka. Defining case objects is simple. See Below Case Objects are quite similar to case classes. They can have members and have some of the same methods like toString, hashCode. Similarly, it is important to understand that some of the methods available in case classes are not available to case objects, for example, apply, unapply. Sealed Case Objects One of the variations of case objects is the sealed case objects. Sealed Case objects are an interesting alternative to the enumeration trait. If you want a peek into scala enumeration trait before diving into sealed case objects, … Read more