Start learning free

LESSON 80 OF 348 · CONDITIONAL STATEMENTS

Chaining Conditionals in Scala in Scala

Lesson

Sometimes we can have more than two possible scenarios which need a different code to be ran. We can add else if statements to allow for as many outcomes as we want:

var language = "Python"
if(language == "Scala") {
    println("It's super popular!")
}
else if(language == "Python") {
    println("It's so simple!")
}
else if (language == "Java") {
    println("It's pretty hardcore!")
}
else {
    println("It's exotic!")
}

In the example above, language == "Scala" evaluates to false, so we move on and enter the following else if.

There, language == "Python" evaluates to true, so we execute what's inside that block and print "It's so simple!".

The rest of the conditions are not evaluated.

In case none of the conditions evaluates to true, then the code in the final else statement would execute. For example, if language was "Go", the program would have printed "It's exotic!"


Assignment
Follow the Coding Tutorial and let's write some chained conditionals.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 3
    Ctrl + Enter to check

    Chaining Conditionals in Scala

    Keep going with ScalaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free