allan.conda
04/15/2022, 10:04 AMval nullableFoo: Any? = null
val nonNullFoo = nullableFoo != null
if (nonNullFoo) {
acceptsNonNullFoo(nullableFoo) // expected Any but is Any?
}
but this works
val nullableFoo: Any? = null
if (nullableFoo != null) {
acceptsNonNullFoo(nullableFoo)
}
🤔Joffrey
04/15/2022, 10:06 AMnonNullFoo
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.allan.conda
04/15/2022, 10:11 AMnonNullFoo
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
if (nonNullFoo && nullableFoo != null)
againVampire
04/15/2022, 10:19 AMacceptsNonNullFoo(nullableFoo!!)
allan.conda
04/15/2022, 10:39 AMnonNullFoo
and got a crash because I forgot about the !!
😄Adam S
04/15/2022, 11:07 AM@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")
}
}
dmitriy.novozhilov
04/15/2022, 12:24 PM