Tom De Decker
03/16/2023, 11:50 AM@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!dmitriy.novozhilov
03/16/2023, 1:10 PMTom De Decker
03/16/2023, 1:38 PM