SeniorZhai
09/06/2022, 9:03 AMif-else-if-elseSam
09/06/2022, 9:06 AMSam
09/06/2022, 9:06 AMSam
09/06/2022, 9:06 AMif (random == 0) {
1L
} else (if (random == 1) {
"1"
} else {
"2"
}.apply {
println(this)
})Sam
09/06/2022, 9:06 AMelse is a single expressionMichael de Kaste
09/06/2022, 9:09 AMwhen statement when you have multiple conditions 🙂Rob Elliot
09/06/2022, 9:12 AMif (random == 0) {
1L
} else {
if (random == 1) {
"1"
} else {
"2"
}.apply {
println(this)
}
}Rob Elliot
09/06/2022, 9:13 AM(
if (random == 0) {
1L
} else if (random == 1) {
"1"
} else {
"2"
}
).apply {
println(this)
}SeniorZhai
09/06/2022, 9:15 AMSam
09/06/2022, 9:17 AMif isn’t an expression. It might be more interesting to compare it to the ternary operator, e.g.
random == 0 ? 1L : random == 1 ? "1" : "2"Rob Elliot
09/06/2022, 9:20 AMwhen (random) {
0 -> 1L
1 -> "1"
else -> "2"
}.apply {
println(this)
}Rob Elliot
09/06/2022, 9:21 AMSam
09/06/2022, 9:22 AMif (condition) expr1 else expr2
so what looks like else if is actually not a ‘real’ language construct, it’s just an else where expr2 happens to be another if expressionAlbert Chang
09/06/2022, 9:23 AM