Search code examples
scala

Scala: if-else expression as left operand, operation is performed only if condition evaluates to false?


Like the following example:

scala> if (true) { 1 } else { 2 } + 3
val res1: Int = 1

scala> if (false) { 1 } else { 2 } + 3
val res2: Int = 5

It seems as if the curly braces are ignored. Wrapping the if-else expression with parentheses seems to work as expected.

scala> (if (true) { 1 } else { 2 }) + 3
val res3: Int = 4

This appears super unintuitive to me. Can someone please help me understand this?


Solution

  • The intuition is that braces simply create a block expression that can be part of a larger expression. They are not part of the if statement.

    The general form of if is

    if (<test>) <expression> else <expression>
    

    In the question the code after the else is a simple expression:

    { 2 } + 3
    

    + has a higher precedence than if/else so it is parsed as

    if (<test>) { 1 } else ({ 2 } + 3)
    

    rather than

    (if (<test>) { 1 } else { 2 }) + 3