https://kotlinlang.org logo
#announcements
Title
# announcements
p

Pere Casafont

07/20/2019, 12:25 PM
I just found something a bit puzzling in the language (thread)
Isn't the compiler being a bit too smart there? Shouldn't this be an error?
weirder:
Copy code
object A {
    val foo: String
    val bar: String
    
    init {
        println(1)
        foo = "hi"
        println(2)
        bar = B.baz
        println(3)
    }
}

object B {
    val baz: String
    val mor: String
    
    init {
        println(4)
        baz = A.foo
        println(5)
        mor = A.bar
        println(6)
    }
}

fun main() {
    println(B.mor)
}
k

karelpeeters

07/20/2019, 12:36 PM
It's not actually being smart, it's easy to get runtime exceptions when doing things like this. It just happens to work out here.
e

egorand

07/20/2019, 1:29 PM
FWIW I don't think it has anything to do with the language/compiler, it's how JVM loads classes and executes initializers
k

karelpeeters

07/20/2019, 1:29 PM
Looks like they put in some effort to make it work the same way on JS though.
e

egorand

07/20/2019, 1:31 PM
But does play.kotlinlang.org compile into JS and run it in the browser, or does it send code to a backend that compiles and runs it on JVM?
k

karelpeeters

07/20/2019, 1:32 PM
Well you can choose between JVM and JS in the gear icon on the right.
h

Hullaballoonatic

07/21/2019, 12:09 AM
object instantiation is lazy
that's the answer to your puzzle
2 Views