Start learning free

LESSON 80 OF 348 · CONDITIONAL STATEMENTS

Chaining Conditionals in Kotlin: else if

Lesson Read the full explanation

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:

val language = "Python"
if (language == "JavaScript") {
    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 == "JavaScript" 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

    KOTLIN · CONDITIONAL STATEMENTS

    Chaining Conditionals in Kotlin, explained

    More than two outcomes

    An if with an else chooses between two paths. Often there are more. A grade might be failing, passing, good or perfect, and each needs its own message. You add as many outcomes as you need by chaining else if branches between the first if and the final else:

    val language = "Python"
    if (language == "JavaScript") {
        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!")
    }
    

    This prints It's so simple!. Kotlin checks the conditions from the top. language == "JavaScript" is false, so it moves to the next one. language == "Python" is true, so that block runs. The rest of the chain is skipped, and the remaining conditions are not even evaluated. With language = "Go", every condition is false, and the final else prints It's exotic!.

    How a chain works

    • Exactly one block runs at most. The first branch whose condition is true wins.
    • The final else is optional. Without it, nothing runs when every condition is false.
    • The conditions are checked in order, so the order of the branches is part of the logic.
    • Each else if only runs when everything above it was false. You can rely on that to keep conditions short.

    Layout in Kotlin

    The usual style keeps else on the same line as the closing brace: } else if (...) {. Kotlin also accepts the else on a new line after the brace, as in the first example of this lesson. Both work, and one habit is enough.

    Chains and rising thresholds

    Because the first match wins, you can write ranges by testing a threshold at a time. The condition grade <= 7 in the second branch does not need to say grade >= 5, because the first branch already handled every grade below 5. Putting the checks in the wrong order breaks this. If you tested grade <= 9 first, a grade of 3 would match it and be called "Good Job".

    Common mistakes

    • Using separate if statements instead of else if. Separate ifs are each checked independently, so several of them can run. With a grade of 6, separate statements if (grade <= 7) and if (grade <= 9) both run and print two messages.
    • Putting the broad condition first. A condition like grade <= 9 catches everything below it too, so it must come after the narrower ones.
    • Writing elseif or else-if. Kotlin spells it as two words, else if.
    • Giving else a condition. A plain else takes no condition. A condition belongs to else if, and the bare else covers everything left over.
    • Forgetting boundary values. "Up to 7" includes 7, so the comparison is <=. With <, a grade of exactly 7 would fall into the next branch.

    The lesson's exercise

    The code starts with val grade = 8. The task is to print one message depending on the grade:

    grademessage
    below 5Failed the test
    5 to 7Passed the test
    8 or 9Good Job
    above 9Perfect
    1. Start with the failing case. Write if (grade < 5) and print "Failed the test". Handling the lowest grades first lets every later branch assume the grade is at least 5.
    2. Add two else if branches. The first tests grade <= 7 and prints "Passed the test". The second tests grade <= 9 and prints "Good Job". Each one runs only when all the checks above it were false.
    3. Finish with an else that prints "Perfect". It catches every grade above 9.
    val grade = 8
    
    if (grade < 5) {
        println("Failed the test")
    } else if (grade <= 7) {
        println("Passed the test")
    } else if (grade <= 9) {
        println("Good Job")
    } else {
        println("Perfect")
    }
    

    With grade = 8, the first condition is false because 8 is not below 5. The second is false because 8 is more than 7. The third is true, so the program prints Good Job.

    Trying other grades

    • 3 prints Failed the test.
    • 5 and 7 print Passed the test.
    • 9 prints Good Job.
    • 10 prints Perfect.

    if as an expression

    In Kotlin, a chain of if and else if can also produce a value, as long as it ends with an else. You could write val message = if (grade < 5) "Failed the test" else if (grade <= 7) "Passed the test" else "Good or better". For a long chain, the next lesson's when is often easier to read.

    Key takeaways

    • else if adds as many outcomes as you need between the first if and the last else.
    • Branches are checked from the top, and the first true condition runs while the rest are skipped.
    • Order the branches so that earlier ones handle the cases that later ones can then ignore.
    • A final else has no condition and catches everything left.
    Keep going with KotlinAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free