I have the following code snippet in Kotlin. I love such code puzzlers, but the result here was too unexpected for me. Can someone describe me why it prints 1
and not 2
?
As shadowing is prohibited in Java - it looks like I completely do not understand how it works in Kotlin.
fun main() {
var a = 1
class A {
var a = 2
fun foo() = a
}
println(A().foo())
}
=========== BONUS ============
Funny thing is that the following code when you will move var a = 1
after the class declaration works fine and prints 2
:
fun main() {
class A {
var a = 2
fun foo() = a
}
var a = 1
println(A().foo())
}
UPD: it looks like Kotlin suddenly decided to play like C++ and have undefined behavior :D
From the Kotlin spec: use this with caution, because in some cases it can be called instead
.
When you do var a = 2
inside the class A
, you're not actually shadowing any variable. You're declaring that a
is a field of class A
, and it defaults to 2.
When you reference a variable in front of a class, Kotlin will add an implicit this
(e.g. a
becomes this.a
) if there is a field with that name but not an upper-level variable with that name. So, the outer a
takes precedence over the field, and you'd have to use this.a
to access the inner a
.
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