I just started to explore the language Kotlin. I'm struggling with inheritance, var&val and side-effects.
If I declare a trait A
with a val x
and override x
in AImpl
it is possible to override it as var
(see code below). Surprisingly the print()
method in A
is affected by the reassignment of x
even though x
is a value in A
. Is this a bug or a feature?
Code:
trait A {
fun print() {
println("A.x = $x")
}
val x : Int;
}
class AImpl(x : Int) : A {
override var x = x; // seems like x can be overriden as `var`
}
fun main(args: Array<String>) {
val a = AImpl(2)
a.print() // A.x = 2
a.x = 3; // x can be changed
// even though print() is defined in trait A
// where x is val it prints x = 3
a.print() // A.x = 3
}
I'm aware of the fact that if I define a
with type A
explicitly it is not allowed to change x
:
val a = AImpl(2) : A
a.x = 3 // ERROR: value x cannot be reassigned
But as the first case shows, inheritance can cause side effects which are clearly not intended in A
. How do I protect values from being changed by inheritance?