This doesn’t compile with error on the first line “Variable ‘b’ must be initialized”
val a = b
val b = “hello”
I think the java version of this error is more informative, “Illegal forward reference”.
But why can’t the compiler figure out the forward reference for me? If I put the declarations in different files the compiler has no problem figuring it out.
1 Like
It is probably a bad idea since basically variable declaration order does matter. Consider this example:
var i = 1
val a = i
i++
val b = 8
Switching a
and b
will give different state. Your suggestion could work in pure functional languages (no it could not, no variables there) or in Pascal-like syntax, where variable declaration is separated from the code, but not in kotlin.
Doesn’t your code only makes sense within a function? You can’t call i++ in a top-level or class scope which is what I what was referring to.
Change it to
val a = i++
val b = i
It still compiles. It is a very bad practice to do so, but the truth is that property initializators basically could change the global and local state and therefore order matters. This situation is rare but sometimes it happens. especially when you try to do GUI initialization or working with resources.