Start learning free

LESSON 69 OF 414 · CONDITIONAL STATEMENTS

If Else in Scala: Choosing Between Two Paths

Lesson Read the full explanation

Many times in our life, not only we choose to do something if a condition is met, but also choose to do something different if that condition is not met. For example:

If I'm tired:
    I take a nap
Otherwise:
    I start coding

If-else Statements:

When a condition for an if statement is true, the block of code following it is executed. What about when that condition is false? Normally nothing would happen.

With an else statement, we can have an alternate block of code to be executed. For example:

val amTired = false
if(amTired) {
    println("I take a nap")
} else {
    println("I start coding")
}

The code above prints "I start coding" since the expression inside the if evaluates to false and so Scala will enter the else statement and execute the code inside it.

An else statement cannot exist without a corresponding if statement. This combination is refered to as an if-else statement.


Assignment
Follow the Coding Tutorial and let's practice with if-else statements!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 1
    Ctrl + Enter to check

    SCALA · CONDITIONAL STATEMENTS

    If Else in Scala, explained

    Doing something when the condition is false

    An if statement runs its block when a condition is true and does nothing otherwise. Often you want a different action in the false case: if I'm tired, take a nap; otherwise, start coding. An else block adds that alternative.

    val amTired = false
    if (amTired) {
        println("I take a nap")
    } else {
        println("I start coding")
    }
    

    Here amTired is false, so Scala skips the first block and runs the one after else. The program prints I start coding.

    An else can't stand alone. It always belongs to the if just before it, and it takes no condition: it runs whenever the if condition is false. Exactly one of the two blocks runs each time.

    Where to put the else

    Scala accepts else on a new line after the closing brace as well as on the same line:

    if (amTired) {
        println("I take a nap")
    }
    else {
        println("I start coding")
    }
    

    Both layouts behave the same way. Most Scala code writes } else { on one line, and the exercise uses that style.

    if-else as an expression

    In Scala an if-else produces a value, so you can pick between two values without a separate variable assignment in each branch:

    val amTired = false
    val plan = if (amTired) "nap" else "code"
    println(plan)
    

    This prints code. Both branches need a value, which is why this form always includes an else. Without one, the false case would produce (), the empty Unit value, which is rarely what you want to store.

    Adding more cases with else if

    When two paths aren't enough, chain checks with else if. Scala tests the conditions from top to bottom and runs the first block whose condition is true. The final else catches everything left over.

    val score = 7
    if (score >= 9) {
        println("Excellent")
    } else if (score >= 5) {
        println("Passed")
    } else {
        println("Failed")
    }
    

    With score equal to 7, the first condition is false and the second is true, so the program prints Passed. The last block is skipped even though it has no condition to check, because a branch earlier in the chain already ran.

    The exercise

    The starter code already has an if:

    val passed: Boolean = false
    if (passed) {
        println("Passed the test")
    }
    

    Because passed is false, running it prints nothing, which leaves the user without an answer. The task is to attach an else that prints "Failed the test". Put else after the } that closes the if block, open a new block with {, add the println, and close it with its own }.

    val passed: Boolean = false
    if (passed) {
        println("Passed the test")
    } else {
        println("Failed the test")
    }
    

    This prints Failed the test. Setting passed to true would print Passed the test instead.

    Common mistakes

    • Giving else a condition. else (passed) is wrong. If you need a second condition, use else if.
    • Putting a statement between the blocks. Any code between the closing } of the if and the else ends the if, and the else has nothing to attach to.
    • Mismatched braces. Every { needs its }. Count them when the compiler reports an error near the end of the file.
    • A different message. The output must match the lesson's text exactly: "Failed the test".

    Key takeaways

    • else runs when the if condition is false.
    • It has no condition and needs a matching if.
    • Exactly one of the two blocks runs.
    • In Scala an if-else is an expression, so it can give a value to a val.
    Keep going with ScalaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free