https://kotlinlang.org logo
#getting-started
Title
# getting-started
m

Mark

05/30/2022, 8:40 AM
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

sanggggg

05/30/2022, 8:43 AM
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

Mark

05/30/2022, 8:44 AM
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

Mark

05/30/2022, 8:56 AM
Yup definitely confusing: https://pl.kotl.in/Mhd5jD9RD
👌 1
e

ephemient

05/30/2022, 9:01 AM
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

Mark

05/30/2022, 9:19 AM
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

sanggggg

06/01/2022, 7:40 AM
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

ephemient

06/01/2022, 8:24 AM
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

Mark

06/01/2022, 1:20 PM
Hmm, marked as duplicate. Actually I had a feeling I’d seen (and starred!) that before.
2 Views