Start learning free

LESSON 68 OF 414 · CONDITIONAL STATEMENTS

If Statements in Scala: Making Decisions

Lesson Read the full explanation

TL ; DR:

  • if statements allow us to build programs that can make decisions based on some conditions. Here is the syntax:

    val isRainy = true
    if(isRainy) {
        println("I bring an umbrella")
    }
    



Full lesson:

As humans, we often make decisions based on conditions. For example, we might go through these decision-making processes during a day:

If it's rainy:
  I bring an umbrella

If I'm hungry:
  I have breakfast
  
If I'm tired:
  I take a nap

We can also tell the computer to make decisions like these in our programs.


If Statements:

if statements allow us to build programs that can make decisions based on some conditions. Here is the syntax:

if(conditions) {
    // instructions
}

The keyword if tells Scala to execute the code inside the curly braces (where we have our Scala comment) only if the conditions defined in the parentheses are met.


Boolean conditions:

The conditions inside if statements are known as Boolean conditions and they may only be true or false.

If the Boolean condition evaluates to true, the program executes the statements inside curly braces. If it evaluates to false, the statements will not execute.

If you check our example, you'll see that all the conditions there (it's rainy, I'm hungry and I'm tired) are Boolean conditions.

Let's turn those decisions into working code using if statements:

val isRainy = true
if(isRainy) {
    println("I bring an umbrella")
}

The code above prints "I bring an umbrella" since the condition in the parentheses evaluates to true

But this code:

val amHungry = false
if(amHungry) {
    println("I have breakfast")
}

prints nothing since amHungry evaluates to false.


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


Hint
Look at the examples above if you get stuck.


STEP 1 OF 3
    Ctrl + Enter to check

    SCALA · CONDITIONAL STATEMENTS

    If Statements in Scala, explained

    What an if statement does

    A program that always does the same thing is limited. An if statement lets code run only when a condition holds, the same way you decide during a day: if it's rainy, bring an umbrella; if you're hungry, have breakfast.

    The shape is always the same: the keyword if, a condition in parentheses, and a block in curly braces.

    if (condition) {
        // instructions
    }
    

    Scala runs the block only when the condition is true. When it's false, Scala skips the block and continues with whatever follows.

    Boolean conditions

    The condition must be a Boolean, a value that is either true or false. It can be a Boolean variable, a comparison such as age >= 18, or any other expression of that type.

    val isRainy = true
    if (isRainy) {
        println("I bring an umbrella")
    }
    
    val amHungry = false
    if (amHungry) {
        println("I have breakfast")
    }
    println("done")
    

    This prints:

    I bring an umbrella
    done
    

    The first block runs because isRainy is true. The second is skipped because amHungry is false, and the program carries on to the last line.

    Only a Boolean will do

    Scala is strict about the condition's type. Unlike some languages, it doesn't treat numbers or strings as "truthy" or "falsy". Writing if (n) where n is an Int fails to compile with a type mismatch: found Int, required Boolean.

    A single = is a related trap. It assigns, while == compares. Writing if (n = 5) doesn't compile either, because an assignment has type Unit and the compiler requires a Boolean. In Scala this slip is caught before the program runs.

    Parentheses and braces

    The parentheses around the condition are required. The braces are optional when the block holds one statement, so if (isRainy) println("I bring an umbrella") works. Braces are still a good habit, because they make it obvious where the block ends when you add a second line later.

    The exercise

    The starter code declares one value:

    val passed: Boolean = true
    

    The task has three steps.

    1. Write the if. passed is already a Boolean, so the condition is just passed. Comparing it with == true adds nothing.
    2. Print inside the block. Put println("Passed the test") between the braces, so it runs only when the condition is true.
    3. Add an else. An else has no condition of its own. It covers every case the if didn't. Write } else { on one line, print "Failed" inside, and close the block.

    The finished code:

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

    With passed set to true it prints Passed the test. Change the value to false and it prints Failed. Exactly one of the two blocks runs, never both and never neither.

    Common mistakes

    • Forgetting the parentheses. The condition always goes in ( ).
    • Using = instead of ==. One assigns, the other compares.
    • Misspelling the message. The text in the quotes is the output, so "Passed the test" and "Passed the Test" are different.
    • Writing a condition after else. else never takes one. A second check needs else if.

    Key takeaways

    • if (condition) { ... } runs the block only when the condition is true.
    • The condition must be a Boolean; Scala has no truthy or falsy values.
    • An else block runs when the condition is false.
    • When the condition is already a Boolean value, use it directly.
    Keep going with ScalaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free