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
truewins. - The final
elseis optional. Without it, nothing runs when every condition isfalse. - The conditions are checked in order, so the order of the branches is part of the logic.
- Each
else ifonly runs when everything above it wasfalse. 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
ifstatements instead ofelse if. Separateifs are each checked independently, so several of them can run. With a grade of 6, separate statementsif (grade <= 7)andif (grade <= 9)both run and print two messages. - Putting the broad condition first. A condition like
grade <= 9catches everything below it too, so it must come after the narrower ones. - Writing
elseiforelse-if. Kotlin spells it as two words,else if. - Giving
elsea condition. A plainelsetakes no condition. A condition belongs toelse if, and the bareelsecovers 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:
| grade | message |
|---|---|
| below 5 | Failed the test |
| 5 to 7 | Passed the test |
| 8 or 9 | Good Job |
| above 9 | Perfect |
- 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. - Add two
else ifbranches. The first testsgrade <= 7and prints"Passed the test". The second testsgrade <= 9and prints"Good Job". Each one runs only when all the checks above it werefalse. - Finish with an
elsethat 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 ifadds as many outcomes as you need between the firstifand the lastelse.- Branches are checked from the top, and the first
truecondition runs while the rest are skipped. - Order the branches so that earlier ones handle the cases that later ones can then ignore.
- A final
elsehas no condition and catches everything left.