https://kotlinlang.org logo
Title
j

Jonathan Ellis

07/26/2022, 4:14 PM
This code prints "0" on JVM and "undefined" on js. In this example it's obvious that I'm forcing something the compiler doesn't like (without the lambda, it will correctly complain that foo is not initialized) but in my actual use case it was not obvious and took a lot of time to track down why js behavior was different than jvm. Is there anything the compiler can do to help with this, the way it does with lateinit?
import kotlin.test.Test

class Undefined {
    init {
        println({ -> foo }.invoke())
    }

    val foo = 0
}

class Foo {
    @Test
    fun testUndefined() {
        Undefined()
    }
}
e

ephemient

07/26/2022, 5:10 PM
on JVM, an uninitialized primitive field contains zero. on JS, anything uninitialized is undefined.
changing
val foo = 100
still results in
0
, so it's the fact that it's inferred as
val foo: Int
that causes the result to be 0 on JVM
j

Jonathan Ellis

07/26/2022, 5:14 PM
you're right, my example didn't make that clear.
e

ephemient

07/26/2022, 5:15 PM
if you explicitly wrote
val foo: Any = 0
then you'd see
null
on JVM