fun main() {
Fun().things()
}
data class Stuff(
val s: String
)
class Fun {
private val stuff: Stuff = createStuff()
private val x: String = "x"
fun things() {
println(stuff.s)
}
private fun createStuff(): Stuff {
return Stuff(x)
}
}
solution
`KotlinNullPointerException`: `null` is passed to non-null parameter `s` in `Stuff.constructor`
The value of `x` is null at the point of Stuff constructor call, because the `Fun` `val`s are initialized in order.
Because it's in a function, Kotlin thinks it's safe, when inlined the problem becomes obvious.
It is standart puzzler with non-initialized property. I dont know whether it exits in Anton's collection, but I have seen it many times in other sources.
What will this print?
solution
`KotlinNullPointerException`: `null` is passed to non-null parameter `s` in `Stuff.constructor` The value of `x` is null at the point of Stuff constructor call, because the `Fun` `val`s are initialized in order. Because it's in a function, Kotlin thinks it's safe, when inlined the problem becomes obvious.Is there anything similar already?