TOTD: Scala - Class Modifiers
Today we're going to confab about class modifiers -- specifically the rules around the final
keyword and inheritance. Assume we have three base classes we can inherit from.
case class CaseBase()
class ClassBase
final class FinalBase // <=== this one is locked via final keyword!
When we attempt to extend a case class with another case class, we are welcomed with a compile time error.
/*
* Won't compile! Reason: case-to-case
* case class CaseChild() extends CaseBase
*
* Won't compile! Reason: locked via 'final'
* class FinalChild extends FinalBase
*/
However, inheriting opposite class types are ok. The caveat is that there can't be more than one case class in the chain.
class ClassChild extends CaseBase // case-to-class
case class CaseChild() extends ClassBase // class-to-case
TL;DR
- case-to-case inheritance is prohibited
- class-to-class is allowed, obviously
- case-to-class is allowed
- class-to-case is allowed
final
blocks all that jazz
A final class member definition may not be overridden, by using the override
keyword, in subclasses. And finally, the final
keyword is redundant for object
definitions. Join us next time when we tackle the trait
keyword and the sealed
modifier.