Rationale behind avoiding Smart cast for mutable properties

Just wanted to add some of the runnable (and editable) examples for fun (taken from this post: Nullable property lazy allocation - #36 by arocnies).

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

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

var foo: Boolean? = true 
    get() = field.also {field = null}
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 }
    }
fun main(args: Array<String>) {
//sampleStart
    if (foo != null) {
        doSomething()
        print("foo: $foo")
    }
//sampleEnd
}

var foo: Boolean? = true

fun doSomething() {
    // doSomething ...
    foo = null
}
3 Likes