Nullable property lazy allocation

That’s awesome! :smile:
I totally forgot about custom getters/setters.

EDIT: I just had to make a runnable example:

fun main(args: Array<String>) {
    //sampleStart
    foo = true

    if (foo != null) {
        println("foo: $foo")
    } //sampleEnd
}

var foo: Boolean? = true 
    get() = field.also {field = null}

And

fun main(args: Array<String>) {
    //sampleStart
    foo = true

    if (foo != null) {
        println("foo: $foo")
        println("foo: $foo")
        println("foo: $foo")
    } //sampleEnd
}

var foo: Boolean? = true 
    get() = when(field) {
        true -> { field = false; true }
        false -> { field = null; false }
        null -> { field = true; null }
    }

^ Of course, any normal method, not just custom getters/setters, that has a side-effect of changing that property could also make the var null after the null check:

fun main(args: Array<String>) {
    //sampleStart
    if (foo != null) {
        doSomething()
        print("foo: $foo")
    } //sampleEnd
}

var foo: Boolean? = true

fun doSomething() {
    // doSomething ...
    foo = null
}
1 Like