https://kotlinlang.org logo
#getting-started
Title
# getting-started
a

allan.conda

04/15/2022, 10:04 AM
Anyone know why this doesn’t work
Copy code
val nullableFoo: Any? = null
val nonNullFoo = nullableFoo != null
if (nonNullFoo) {
   acceptsNonNullFoo(nullableFoo) // expected Any but is Any?
}
but this works
Copy code
val nullableFoo: Any? = null
if (nullableFoo != null) {
   acceptsNonNullFoo(nullableFoo)
}
🤔
j

Joffrey

04/15/2022, 10:06 AM
The compiler doesn't analyze the program to this extent (as far as flow analysis is concerned), so it doesn't link the null check on
nonNullFoo
boolean variable to the fact that
nullableFoo
is not null when considering the
if
statement. In the second snippet, it is able to detect that because it's a direct null check on that variable, so smart casting can work.
a

allan.conda

04/15/2022, 10:11 AM
I see. In actual
nonNullFoo
boolean has more conditions, but
nullableFoo != null
seems should be true 100% of the time. Any tips how to handle this in code? It feels weird to have to do
Copy code
if (nonNullFoo && nullableFoo != null)
again
v

Vampire

04/15/2022, 10:19 AM
acceptsNonNullFoo(nullableFoo!!)
a

allan.conda

04/15/2022, 10:39 AM
^ that bit me in the a$$ too quickly. I removed
nonNullFoo
and got a crash because I forgot about the
!!
😄
a

Adam S

04/15/2022, 11:07 AM
have you looked at contracts? https://www.baeldung.com/kotlin/contracts You can write a custom 'validate not null' method, which the compiler will understand
Copy code
@ExperimentalContracts
private fun validate(request: Request?) {
    contract {
        returns() implies (request != null)
    }
    if (request == null) {
        throw IllegalArgumentException("Undefined request")
    }
    if (request.arg.isBlank()) {
        throw IllegalArgumentException("No argument is provided")
    }
}
d

dmitriy.novozhilov

04/15/2022, 12:24 PM
Such smartcasts will work in K2 compiler
🆒 8
2 Views