Scala Tutorials Part #10 - Case objects in scala
Originally Posted On : 20 Feb 2017
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.
Case objects are pretty useful if you want the boilerplate stuff that is there for case classes.
They can be created as below.
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
hashCodebased on murmur hash
- Case object/Case class is serializable by default
We can verify that it is
Serializable with the below code example.
If we want the regular
Object to become serializable then it can extend the
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.