Hi there! I've recently been experimenting a bit w...
# getting-started
t
Hi there! I've recently been experimenting a bit with Kotlin's Contract API but I wasn't able to figure out why some smart casting seemed a little inconsistent. I've added an example in this thread:
Here's an example:
Copy code
@OptIn(ExperimentalContracts::class)
fun myTest(foo: String?): String? {
    contract {
        returnsNotNull() implies (foo != null)
    }
    return foo
}

fun myFunction(foo: String?) {
    myTest(foo) ?: return

    foo.length // Error: requires safe or non-null asserted call

    if (myTest(foo) != null) {
        foo.length // No error
    }
}
In this snippet I have a dummy function
myTest
that which guarantees that if a non-null value is returned, the given parameter is also non-null. This should in theory mean that the first line of
myFunction
"guards" the
foo
value and that
foo
should be guaranteed to be non-null on all lines after that. Instead, this produces an error on the
foo.length
call, implying that no smart cast was possible. If we exlicitly perform this test in an if statement, however, the smart cast succeeds and the compiler seems to know that
foo
can no longer be null. Does anyone know if this is a limitation in how the compiler treats the
?: return
as opposed to an if statement? Or am I overlooking something? Thanks for the help!
d
This is a bug, which is fixed in K2 compiler
t
Good to know, thanks!