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.

case object Red

//Prints - Red
println(Red.toString)

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, this is the link. Case objects do address some of the shortcomings of the Scala enumerations.

Let’s define a simple sealed case object. See Below

sealed trait Color
case object Red extends Color
case object Blue extends Color
case object Green extends Color
case object Yellow extends Color
//Prints - Red
println(Red.toString)

If you observer we create a sealed trait and then extend that to create case objects.

It is also possible to create case objects which can have members. The way to define is slightly different. By defining a sealed abstract class rather than a sealed trait. See Below

sealed abstract class Color(val desc:String)
case object Red("I am Red") extends Color
case object Blue("I am Blue") extends Color
case object Green("I am Green") extends Color
case object Purple("I am here too!") extends Color

//Prints - Red
println(Red.toString)

//Prints - I am Red
println(Red.desc)

Sealed case objects also resolve one of the issues faced by Scala enumeration trait of non-exhaustive compilation. See Below

sealed abstract class Color
case object Red extends Color
case object Blue extends Color
case object Green extends Color
case object Purple extends Color

def findColor(c:Color):String={
  c match {
    case Red => "Found Red"
    case Green => "Found Green"
  }
}

println(findColor(Red))

When you compile the code below it should give you a warning message that the code check is not exhaustive. See Below

Even though sealed case objects are a step up. They do not resolve all the issues. Rather they do not provide some of the basic enumeration methods like sorting, extracting a list of values. So if you need a list of values or sorting then sealed case objects are not for you. But otherwise, they are quite good.

A much better approach to enumeration is using the “Enumeratum” library which has become a standard of sorts amongst the developers in case you are using enumerations.

Till next time….bye!!

Leave a Comment