Consider two classes:
abstract class ParentRepository {}
class ChildRepository : ParentRepository {}
abstract class ParentClass {
protected abstract var repository: ParentRepository
}
class ChildClass : ParentClass {
override var repository: ChildRepository
}
The last part won't work:
override var repository: ChildRepository
It will complain:
Type of 'repository' doesn't match the type of the overridden var-property 'protected abstract var repository: ParentRepository
I understand the problem, but I don't see the reason why this shouldn't work – ChildRepository is an instance of ParentRepository and this is a common thing I am used to from Java.
In Java, every method is virtual by default; therefore, each method can be overridden by any derived class. In Kotlin, you would have to tag the function as being opened to redefine it.
To override a property of the base class in the derived class, we use the override keyword.
To override a method of the base class in the derived class, we use the override keyword followed by the fun keyword and the method name to be overridden.
Before we proceed, I must note that because classes can have state and initialization logic (including side-effects), Kotlin does not allow true multiple inheritance as that could cause havoc in slightly more complex class hierarchies (it does allow declaring properties and implementing methods in interfaces, though, ...
You have to declare repository
as val. You can still override it as var:
protected abstract val repository: ParentRepository
override var repository: ChildRepository
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With