Edwar D Day
02/03/2022, 11:54 AMEdwar D Day
02/03/2022, 11:54 AM@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
}
}
dmitriy.novozhilov
02/03/2022, 12:09 PMfun 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)Edwar D Day
02/03/2022, 12:51 PMDominaezzz
02/03/2022, 1:29 PM