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.