Struggling to understand why the overriding works ...
# announcements
m
Struggling to understand why the overriding works with val but not with var. What changes with var? This works:
Copy code
class A (
    override val values: List<A>
) : B

interface B {
    val values: List<B>
}
This does not:
Copy code
class A (
    override var values: List<A>
) : B

interface B {
    var values: List<B>
}
l
Assume this code does work. In the second one, you can put values from some value with type `List<B>`: for example,
Copy code
class C : B { ... }
val a: A = A(...)
val b: B = a
b.values = listOf<B>(C())
This becomes available, then when getting from `a.values`(which is just alias to
b.values
with different type), values is expected to be instance of List<A>; in fact it isn't.
Copy code
a.values[0] // not the instance of A
m
Ah, I see. That makes sense, thank you!
👍 1
j
I would have never guessed that. Great explanation @lhwdev
👍 1
r