Is this a compiler bug? ```fun main() { val x ...
# compiler
g
Is this a compiler bug?
Copy code
fun main() {
    val x = 0
    val a = if (x == 0) {
        "A"
    } else if (x == 1){
        "B"
    } else {
        "C"
    }.also {
        println("Executing also")
    }
    println(a)
}
If the code enters on the first if (
x == 0
) the also block won’t be executed. Shouldn’t it be always executing?
c
the
also
is on the inner if statement
I very rarely use if/else constructs - they’re much better represented in other ways. In your example this is equivalent, without the nested blocks and surprises on scoping:
Copy code
fun main() {
    val x = 0

    val w = when(x) {
        0 -> "A"
        1 -> "B"
        else -> "C"
    }.also { println("Executing also") }
    println(w)
}
Original code with the scoping fixed:
Copy code
val a = if (x == 0) {
        "A"
    } else {
        if (x == 1){
        	"B"
    	} else {
        	"C"
    	} 
   	}.also {
        println("Executing also")
    }
g
Thanks. Yes, I agree that this code isn’t ideal, I was experimenting with an example from a Google codelab and noticed this corner case if I added an else-if in this block. I expected the compiler would apply the
also
to the whole if, else-if block, not only on the inner if statement.
I just wanted to double check if this was correct.
c
its correct behaviour; the confusing scoping of if/else leads to surprises here. Fully scoping the else block makes it clear which expression
.also
applies to.
tl;dr:
.also
is applied to the left-hand-side expression, in this case the if/else that precedes it.
thank you color 1
e
https://youtrack.jetbrains.com/issue/KT-16275 that's how the language works
c
there’s almost always a better representation of logic than if/else; failing something better, at least adopt a coding style / linter that requires braces for if/else to avoid confusion.
e
I don't think anybody's style guide require the extra braces and nesting of
Copy code
if (...) {
    ...
} else {
    if (...) {
        ...
    } else {
        ...
    }
}
instead of the much more common
Copy code
if (...) {
    ...
} else if (...) {
    ...
} else {
    ...
}
IMO the language spec should be changed to remove this footgun but since that's a breaking change, at a minimum IDE should warn about a post-else function call. unfortunately it doesn't yet https://youtrack.jetbrains.com/issue/KTIJ-22055
💯 1