fun smartCast(
condition1: String?,
condition2: String?
): String? {
if (condition1 == null || condition2 == null) return null
return dummy(condition1) // OK, smart cast succeed
}
fun smartCastFailed(
condition1: String?,
condition2: String?
): String? {
val checkCondition = condition1 == null || condition2 == null
if (checkCondition) return null
return dummy(condition1) // KO, smart cast fails
}
fun dummy(condition: String): String = TODO("do something with condition")
That might seem like a stupid example but I had a bunch of conditions that would not fit in one line and I also wanted to explicit a bit the check with the variable.
I assume this type of optimization is a bit hard for the compiler?
Any way around that? I guess using
!!
is fine since I’m sure the condition is not null.
d
dmitriy.novozhilov
09/19/2022, 3:58 PM
Such smartcasts are supported in K2 compiler
j
Jérémy CROS
09/19/2022, 4:10 PM
oh nice, thanks for the answer! i’ll go with
!!
for now then
and hopefully, we’ll get a
!! no needed
warning in AS after we move to K2 so we remember to do some cleanup 😉