https://kotlinlang.org logo
#intellij
Title
# intellij
l

LastExceed

05/15/2021, 9:49 AM
why is
foo
being printed here even though x is overriden ? edit: oops wrong channel
d

diesieben07

05/15/2021, 9:52 AM
What you are overriding is the getter for the property. You need to realize that a property can be made up of multiple parts (at least a getter, but possibly a backing field and a setter if it's a
var
). In your case both
A.x
and
B.x
have a backing field which is initialized. The initializer is not something that is overridden and neither is the backing field. Both exist in both
A
and
B
.
l

LastExceed

05/15/2021, 9:53 AM
oh interesting, so there's
super.x
which still stores 1
TIL
ty
u

uli

05/15/2021, 10:30 PM
No.
The initializer is not something that is overridden and neither is the backing field.
Meaning there is only one common
x
for
A
and
B
. But this
x
is initialized twice, leaving it with it's last value (2). But keeping the side effects from all initializers
e

ephemient

05/16/2021, 1:11 AM
no, @LastExceed's previous statement was correct. as written, there's a separate backing field in both A and B. A's backing field is initialized in A's constructor, and B's backing field is initialized in B's constructor. B's getter overrides A's getter, so A's backing field cannot be accessed externally (except by reflection), but from within B, it can be accessed through the super getter
super.x
.
@uli remember that
val x = 1
does multiple things: - declare a private backing field - declare a public getter - adds initialization to the (primary) constructor an
override val
can only override the getter, none of the others.
3 Views