Goldcrest
04/27/2022, 3:32 AMval nonNullVal =
if(condition1) {
someOperation.get() // null
} else if (condition2) {
someOperationTwo.get() // null
} else {
null
} ?: defaultVal
When condition 1 is true our nonNullVal
evaluates to null
.
When condition 1 is false and condition 2 is true our nonNullVal
evaluates to defaultVal
What is happening? X_x I would just like to get a grasp of what is going on internally.
Any help is appreciated! Thanks!Jacob
04/27/2022, 4:49 AMelse {if...}
ephemient
04/27/2022, 5:54 AMif (condition1) { block } else expression
where expression
is
if (condition2) { block } else { block } ?: defaultVal
Goldcrest
04/27/2022, 6:03 AMval nnv =
( if(a) null
else if(b) null
else null )
?: defaultVal
is actually
val nnv = if(a) null else (if(b) null else null ?: defaultVal)
?!
That explains it! Thanks you so much! I’m glad I asked 😃ephemient
04/27/2022, 6:04 AMwhen
to get your desired behavior,
when {
condition1 -> ...
condition2 -> ...
else -> null
} ?: defaultVal
when
or
inline fun <R> runIf(cond: Boolean, then: () -> R): R? = if (cond) then() else null
val nonNullVal = runIf(condition1) {
someOperation.get() // null
} ?: runIf(condition2) {
someOperationTwo.get() // null
} ?: defaultVal
as borrowed from https://youtrack.jetbrains.com/issue/KT-43712Goldcrest
04/27/2022, 8:37 AMwhen
expression instead of else if
whenever possible.