Please can someone explain what is happening here:...
# getting-started
m
Please can someone explain what is happening here: https://pl.kotl.in/3lF-S9LUl
Copy code
var check1 = true
var check2 = false
val test = if (check1) {
    null
} else if (check2) {
    listOf("foo")
} else {
    listOf("bar")
}.map { 2 }
println(test)
It seems we don’t need to use safe null on the
map
call. However, if we remove the middle branch, then we do need it:
Copy code
var check1 = true
var check2 = false
val test = if (check1) {
    null
} else {
    listOf("bar")
}?.map { 2 }
println(test)
In both cases (without the
map
), the type of
test
is
List<String>?
s
I think it’s because the second code is recognized as below
Copy code
fun main() {
    var check1 = true
    var check2 = false
    val test = if (check1) {
        null
    } else {
        if (check2) {
        	listOf("foo")
	    } else {
        	listOf("bar")
    	}.map { 2 }
    }
    println(test)
}
m
Yes, it looks to be the case. But is it intended, and isn’t it confusing?
👀 1
it's "intended" as far as being consistent with how the Kotlin grammar is defined, but it's definitely confusing and I think the grammar should change
🙏 2
m
Yup definitely confusing: https://pl.kotl.in/Mhd5jD9RD
👌 1
e
whether or not kotlin gets fixed (which it may not as this would be a breaking change), this is better written
Copy code
when {
    check1 -> 1
    check2 -> 2
    else -> 3
}.let { println("got $it") }
👍 2
m
I updated the sample code https://pl.kotl.in/SVXHS8mSn to simplify it a bit. It’s so easy to introduce a bug this way. Judiciously switching to
when
instead of
else if
does sound like the more sensible approach
👍 1
s
It’s quite confusing 😢 I think it’d be good to add it as a lint rule. (like warning referenced consecutive if elses) What do you guys think about this? If agreed, I’ll report the issue to detekt
e
I filed https://youtrack.jetbrains.com/issue/KT-52608/Confusing-precedence-after-chained-if-else asking for a change in Kotlin itself, but if that doesn't go anywhere then linters like ktlint or detekt are the next best place.
🙏 2
m
Hmm, marked as duplicate. Actually I had a feeling I’d seen (and starred!) that before.