I have a question about contracts. For me it looks...
# stdlib
e
I have a question about contracts. For me it looks like the implies result can only be handled directly and not with an intermediate variable. (code in thread)
Copy code
@OptIn(ExperimentalContracts::class)
fun Any.plus42(): Int? {
    contract {
        returnsNotNull() implies (this@plus42 is Int)
    }
    return (this as? Int)?.plus(42)
}
fun main1() {
    val a: Any = ""
    val b = a.plus42()
    if (b != null) {
        println(a + b) // compilation error unresolved reference
    }
}
fun main2() {
    val a: Any = ""
    when (val b = a.plus42()) {
        null -> Unit
        else -> println(a + b) // everything works fine
    }
}
d
Actually it's not about contracts but about smartcast engine itself. If rewrite your example without any contract calls iw still won't work
Copy code
fun test(s: String?) {
    if (s != null) {
        s.length // smartcast
    }

    val b = s != null
    if (b) {
        s.length // no smartcast
    }
}
But the good news is that Data flow analyzer was improved in K2 compiler, so such smartcasts will work with it (both examples, your and mine)
K 1
e
Ahh, thanks
d
Woah, that's big news!