Go Back

Scala class inherit or extend another case class not possible

1/11/2023
All Articles

#Scala case class inherit , #extend , #case class , #case class #inheritance #code #coding_question

Scala class  inherit or extend another case class not possible

Scala Case Class  inherit or extend of another case class is not possible

 
If a case class could inherit or extend another case class,
it should introduce ambiguity in how these features should be inherited and behave,
potentially leading to unexpected behavior and complications.
 
As per the update in September 2021, 
Scala does not allow case classes to directly inherit or extend from other case classes. 
This restriction is enforced by the Scala language design.
 
Case classes are designed to be used primarily for modeling immutable data means object,
and they come with some predefine  features like automatic generation of accessor methods,
equality checks, hash code generation,
and pattern matching support. 
These features are generated based on the constructor parameters of the case class.
 
If you need to do a inhertance and share common functionality between case classes, you can use traits or abstract classes. 
Traits can provide a way to share behavior, 
while abstract classes can provide both shared behavior and fields that need to be implemented by the subclasses.
 
1 ) Example for case class which giving error in below code : 
 
case class Student(identifier: String) {}
 
case class SportTeam (salary: Long) extends Student
 
 
In this example , we can not used Student  class as parent class  for inheritance , It is not possible that we can not  inherite another case class.
 
 

If you want to inherite then you can create Trait  :-

 
2) Example of case class which is inherit parent Trait
 
//Here we create Student Trait
 
trait Student{
   def identifier: String
}
 
 
 
Here we create class which is extends Student
 
case class SportTeam(identifier: String, salary: Long) extends Student
 
 
 

Case classs not able to extend of another case class because of  following -

 
  • It led to wrong circumstances and unexpected behaviour. 
  • It produce issue in multiple problems in the pattern matcher.
  • Case class most consistent with inheritance would violate the spec.
  • Scala doesn’t generate a copy method if one already exists in the class/traits the case class inherits.
 
 

Conclusion :

 
Remember that language features and limitations may change in newer versions of Scala, 
Need to verifying  latest Scala documentation or language specification for the most up-to-date information on topic of  case class.

Article