Hi there! I've recently been experimenting a bit w...
# getting-started
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
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
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
"guards" the
value and that
should be guaranteed to be non-null on all lines after that. Instead, this produces an error on the
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
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!
This is a bug, which is fixed in K2 compiler
Good to know, thanks!