Giovanni Marques
07/22/2024, 5:37 PMfun main() {
val x = 0
val a = if (x == 0) {
"A"
} else if (x == 1){
"B"
} else {
"C"
}.also {
println("Executing also")
}
println(a)
}
If the code enters on the first if ( x == 0
) the also block won’t be executed. Shouldn’t it be always executing?Chris Lee
07/22/2024, 5:44 PMalso
is on the inner if statementChris Lee
07/22/2024, 5:48 PMfun main() {
val x = 0
val w = when(x) {
0 -> "A"
1 -> "B"
else -> "C"
}.also { println("Executing also") }
println(w)
}
Chris Lee
07/22/2024, 5:51 PMval a = if (x == 0) {
"A"
} else {
if (x == 1){
"B"
} else {
"C"
}
}.also {
println("Executing also")
}
Giovanni Marques
07/22/2024, 5:52 PMalso
to the whole if, else-if block, not only on the inner if statement.Giovanni Marques
07/22/2024, 5:52 PMChris Lee
07/22/2024, 5:53 PM.also
applies to.Chris Lee
07/22/2024, 5:54 PM.also
is applied to the left-hand-side expression, in this case the if/else that precedes it.ephemient
07/22/2024, 6:33 PMChris Lee
07/22/2024, 6:38 PMephemient
07/22/2024, 6:40 PMif (...) {
...
} else {
if (...) {
...
} else {
...
}
}
instead of the much more common
if (...) {
...
} else if (...) {
...
} else {
...
}
ephemient
07/22/2024, 6:42 PM