Is `foo` being `null` inside the init block expect...
# announcements
j
Is
foo
being
null
inside the init block expected behavior? Doesn't seem right for a property that's declared not null. Printing
foo
directly results in an error. Run code in kotlin playground
e
what were you expecting?
j
There could be some kind of error as foo is not declared as nullable. Accessing foo directly in the init block results in an error.
2
e
ok understandable, but to implement that, it would impact the code when run outside of the constructor too
j
Could you explain why it works in the function and why it doesn't when accessed directly? Not very familiar with kotlin's property initialization rules.
e
if you write
println(foo)
, it's statically resolved to
fun println(message: String)
, where Kotlin applies a null check
if you write
"$foo"
, there's no null check involved there
as part of Java object initialization, all fields start out with default values
j
"$foo"
doesn't seem to work in the init block.
e
yes, same as Java - all fields must be initialized before use
however, outside of the constructor, everything assumes that the object is initialized
j
I see
I will take note of this behavior in the future, thanks!
a
Put foo before init
Although not documented (i think), Its a known from a long time...
p
If you make foo variable as lateinit, then it throws an error
e
ditto
var foo: String by Delegates.notNull()
. the downside to both is that the compiler stops enforcing that the field is initialized in
init
, and every single access has to pay the cost of checking if it's initialized
a
init and constructor blocks are evaluated from top to bottom, so the init block runs before the constructor block. Didn't test, but placing the init block below should work as expected [https://kotlinlang.org/docs/reference/classes.html#secondary-constructors] Edit: nop, forget that, init are always evaluated before secondary constructors