Hello friends, as discussed in the previous blog we know what are case classes and what boilerplate code do they generate.
Now in this blog, we will be discussing case class inheritance, how it can be achieved as the case to case inheritance is prohibited due to the equals and hashcode method case classes generate. We will also be telling the bad side of case classes.
Case class inheritance breaks equivalence relation (symmetric and transitive). Any case class successor which constricts a definition area must redefine the equality because pattern matching must work exactly as equality.
Now the question arises, how inheritance can be achieved in case classes. The answer is simple: Case Class can extend another Class, trait or Abstract Class.
Using Abstract Class-
- Create an abstract class which encapsulates the common behavior used by all the classes inheriting the abstract class.
- Extend abstract class and create a case class extending the abstract class and implementing the method.
We don’t need to create companion object for the DebitCard case class as it will automatically provide the companion object.
- Instantiate Card object by using DebitCard case class and specifying the type of object to be that of the base type.
Now you are ready to use the DebitCard case class and can add more case classes extending abstract class Card such as CreditCard.
Using Trait –
A Case Class or Case Object can extend a Trait.
- Create a trait using trait keyword which contains methods you want the inherited classes to implement.
- Create case class which extends the trait and overrides the variables and methods defined in the trait.
We don’t need to override the methods as id and content parameters are defined as methods that implicitly override Message’s methods.
- Create an object of DefaultMessage which is of type Message(i.e. the trait case class is extending)
Similarly, classes can also be used to implement case class inheritance.
Case classes come with few disadvantages which were not discussed earlier:
- Scala Compiler adds some additional functionality by extending Product trait of scala. Most of the time, it is not useful.
- Case Class equals only considers params from first parameter lists.
Hope you found this blog helpful and interesting.
Thanks for reading!