Scala Tutorials Part #10 - Case objects in scala

Case Objects

We have seen objects and case classes before. Case objects are a mix of both i.e it is a singleton similar to an object and with lot of boilerplate as in a case class. The only difference is that the boilerplate is done for an object instead of a class.

This is part 10 of the scala tutorial series. Check here for the full series.

: This article has been translated to chinese by ChanZong Huang, you can check it out here

Index

Case objects are pretty useful if you want the boilerplate stuff that is there for case classes.

They can be created as below.

case object CaseObjectDemo { println ( "I am a case object" ) }

When you compare the decompiled version of a case object with a case class then you will be able to see the differences.

Things that are missing in case objects.

Apply, Un-apply methods. We will see about this later

There are no copy methods since this is a singleton

No method for structural equality comparison

No constructor as well

The missing pieces are the ones that are actually not needed when compared to case classes.

We can clearly see what is being generated in the decompiled class when compared to a regular Object .

toString method

method hashCode based on murmur hash

based on murmur hash Case object/Case class is serializable by default

We can verify that it is Serializable with the below code example.

//Will print false println ( SerializationExample . isInstanceOf [ Serializable ]) //Will print true println ( CaseObjectSerializationExample . isInstanceOf [ Serializable ]) object SerializationExample { } case object CaseObjectSerializationExample { }

If we want the regular Object to become serializable then it can extend the Serializable trait.

//Will print true since it extends the Serializable trait println ( SerializationExample . isInstanceOf [ Serializable ]) //Will print true println ( CaseObjectSerializationExample . isInstanceOf [ Serializable ]) object SerializationExample extends Serializable { } case object CaseObjectSerializationExample { }

We have reached the end of the article. This was a pretty short one and we saw that there is something called case object and why it exists.

The syntactic sugar that case objects offer over regular objects can be argued when comparing with its counterpart i.e case classes. At first sight they do not seem to have much advantages, but that is not true.

In the following tutorials we will see usages of case objects where the syntactic sugar is actually turned into good, readable code, particularly in two scenarios

1) Where we can do pattern matching with case classes and case objects

2) Using case objects as the base structure for Enumerations in scala

These are advanced topics requiring knowledge of various other functional programming concepts. We will conquer them one at a time.

Stay tuned