I found this problem when I was using `if-else-if-...
# getting-started
s
I found this problem when I was using
``if-else-if-else``
s
This is just an order of operations thing
adding parentheses helps to clarify what’s going on
Copy code
``````if (random == 0) {
1L
} else (if (random == 1) {
"1"
} else {
"2"
}.apply {
println(this)
})``````
Everything after the first
``else``
is a single expression
m
chained if-else statements have been discussed before, but consider using a
``when``
statement when you have multiple conditions 🙂
r
So his first was equivalent to this?
Copy code
``````if (random == 0) {
1L
} else {
if (random == 1) {
"1"
} else {
"2"
}.apply {
println(this)
}
}``````
👍 1
Copy code
``````(
if (random == 0) {
1L
} else if (random == 1) {
"1"
} else {
"2"
}
).apply {
println(this)
}``````
👍 1
s
Is this a feature of kotlin? I'm not sure it's the same with other languages.
s
Well, in many languages
``if``
isn’t an expression. It might be more interesting to compare it to the ternary operator, e.g.
Copy code
``random == 0 ? 1L : random == 1 ? "1" : "2"``
r
Following up on Michael de Kaste's observation, this is the most readable, terse and least unexpected way of expressing it:
Copy code
``````when (random) {
0 -> 1L
1 -> "1"
else -> "2"
}.apply {
println(this)
}``````
👌 1
That was interesting, thanks all - I wasn't aware of that order of precedence in if / else expressions.
s
The basic principle of `if`/`else` is:
Copy code
``if (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``
expression
👍 1
a