Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Type safe code #73

Open
TWiStErRob opened this issue Jul 15, 2020 · 1 comment
Open

Type safe code #73

TWiStErRob opened this issue Jul 15, 2020 · 1 comment

Comments

@TWiStErRob
Copy link
Contributor

TWiStErRob commented Jul 15, 2020

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 vals 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
Copy link

rpuxa commented Jul 16, 2020

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants