Shreyas
11/19/2024, 4:08 PMJoffrey
11/19/2024, 4:09 PMelse
are considered to be a lambda expression due to the +
.
This would make is there
part of the else
clause:
else ({ "C" } + " is there")
Joffrey
11/19/2024, 4:11 PMGleb Minaev
11/19/2024, 4:11 PMif (...) { ... } else if (...) { ... } else {...} + "..."
is equivalent to
if (...) { ... } else { if (...) { ... } else { ... } + "..."}
.Gleb Minaev
11/19/2024, 4:16 PMwhen {
... -> "..."
... -> "..."
else -> "..."
} + "..."
Shreyas
11/19/2024, 4:18 PMJoffrey
11/19/2024, 4:20 PM+
applies to the last if
expression, and you would need clarifying parentheses (or braces) in this case to make it concatenate with both `if`s. But as Gleb rightfully said, in that case it would be much better to use a when
, because you really want to express a single thing with multiple conditions, not nested ifs.Klitos Kyriacou
11/19/2024, 4:32 PMif ... else if ... else
- as if else if
was a thing. It isn't. It is in some other languages, such as Python (where it's written elif
). But in Kotlin, there is no else if
. It's just an else
whose else-clause happens to start with an if
.Joffrey
11/19/2024, 4:35 PMif
chain (with clarifying braces/parentheses):
if (a == "a") {
"A"
} else {
(if (a == "b") "B" else "C") + " is there"
}
This is probably not what you wanted to express.Ankur Patel
11/20/2024, 4:55 AMfun main() {
val a = "c"
val b =
(if(a == "a"){
"A"
} else if(a == "b"){
"B"
} else {
"C"
}) + " is there"
println(b)
}
This will works well with add the bracket for condition and the other string with + sign.