Reputation: 12416
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.
Upvotes: 9
Views: 9880
Reputation: 39843
You have to consider that in Kotlin properties are a set of getters and setters. While a val
only has a getter, a var
also defines a setter. Thus you'd be able to set repository
to a ParentRepository
instance which might not be an instance of ChildRepository
.
If you consider the variances for generics, you'll see the same behaviors. While you can use covariance <out T>
for getters, you have to use contravariance <in T>
for setters.
Upvotes: 8
Reputation: 2556
You have to declare repository
as val. You can still override it as var:
protected abstract val repository: ParentRepository
override var repository: ChildRepository
Upvotes: 18