Here why the "is there" string not get concatenate...
# getting-started
s
Here why the "is there" string not get concatenated? Slack Conversation
j
Maybe the braces of the last
else
are considered to be a lambda expression due to the
+
. This would make
is there
part of the
else
clause:
Copy code
else ({ "C" } + " is there")
By the way, please don't post images of code. They are not searchable, and I can't run your example or modify it/make suggestions. You're already using the playground, so you can also share a playground link directly using the ๐Ÿ”— Copy link button in the top right
๐Ÿ‘† 1
g
I think it's because
if (...) { ... } else if (...) { ... } else {...} + "..."
is equivalent to
if (...) { ... } else { if (...) { ... } else { ... } + "..."}
.
๐Ÿ‘ 2
That's why the concatenation is applied only to one of the last two alternatives but not to one of the all three of them. It' better to write
Copy code
when {
    ... -> "..."
    ... -> "..."
    else -> "..."
} + "..."
โž• 2
s
Code: fun main() { val a = "b" val b = if(a == "a"){ "A" } else if(a == "b"){ "B" } else { "C" } + " is there" println(b) }
j
I think Gleb's right. It's probably just that the
+
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.
๐Ÿ‘ 2
k
The problem is caused by our mental image of
if ... 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
.
๐Ÿ‘ 1
j
@Shreyas in case it wasn't clear, here is another way to write your current
if
chain (with clarifying braces/parentheses):
Copy code
if (a == "a") {
    "A"
} else {
    (if (a == "b") "B" else "C") + " is there"
}
This is probably not what you wanted to express.
plus1 1
a
Copy code
fun 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.
๐Ÿ‘ 1