angryziber / kotlin-puzzlers

A collection of Kotlin Puzzlers
422 stars 58 forks source link

Type safe code #73

Open TWiStErRob opened 4 years ago

TWiStErRob commented 4 years ago

What will this print?

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.

Is there anything similar already?

rpuxa commented 4 years ago

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.