What if-else does
An if statement runs a block of code only when its condition is true. When the condition is false, the block is skipped and nothing happens. Often that isn't enough: you want one thing to happen when the condition holds and a different thing when it doesn't. That is what else adds.
In plain words: if I'm tired, I take a nap, otherwise I start coding. In Kotlin:
val amTired: Boolean = false
if (amTired) {
println("I take a nap")
} else {
println("I start coding")
}
Because amTired is false, Kotlin skips the first block and runs the one after else. The program prints I start coding. Exactly one of the two blocks runs, never both and never neither.
The syntax
- The condition goes in parentheses after
if, and it must be aBoolean. - Each branch is a block in curly braces.
elsehas no condition and no parentheses. It runs whenever theifcondition wasfalse.elsecan't stand alone. It always belongs to theifright before it.
The convention is to write else on the same line as the } that closes the if block, as in } else {.
The exercise
The lesson starts with an if and no else:
val passed: Boolean = false
if (passed) {
println("Passed the test")
}
Since passed is false, this program prints nothing at all. The task is to make it report a result in that case too. Attach an else branch to the existing block and print "Failed the test" inside it:
val passed: Boolean = false
if (passed) {
println("Passed the test")
} else {
println("Failed the test")
}
Now the output is Failed the test. Change passed to true and the first branch runs instead, printing Passed the test. Try both values in the editor above to see each branch run.
if-else as an expression
In Kotlin, if is an expression: it produces a value, so you can assign its result. When you use it that way, else is required, because the expression needs a value for both outcomes:
val amTired = false
val plan = if (amTired) "nap" else "code"
println(plan)
This prints code. For this lesson the statement form with blocks is what you need, but the expression form is how Kotlin replaces the ternary operator found in other languages.
Braces and indentation
Kotlin lets you drop the braces when a branch holds a single statement, as in if (passed) println("Passed") else println("Failed"). Keep the braces while you are learning. They make it obvious which lines belong to which branch, and adding a second statement later won't silently fall outside the branch. Indent the code inside each block by four spaces. The compiler ignores indentation, but it lets a reader see the structure at a glance.
More than two outcomes
When two branches aren't enough, chain further checks with else if. Kotlin tests the conditions from top to bottom and runs the first block whose condition is true. The final else catches everything that is left:
val hour = 20
if (hour < 12) {
println("Morning")
} else if (hour < 18) {
println("Afternoon")
} else {
println("Evening")
}
With hour equal to 20, both conditions are false, so the program prints Evening. Once one branch has run, the rest of the chain is skipped.
Common mistakes
- Putting a condition on
else. Writingelse (passed == false)is an error. If you need a further test, useelse if, which is a newifinside the else. - Using a non-Boolean condition. Kotlin doesn't treat numbers or strings as true or false.
if (x)with anIntxis a compile error: condition type mismatch, inferred type isIntbutBooleanwas expected. - Writing
=instead of==.=assigns and==compares. An assignment isn't allowed inside the condition, so Kotlin reports an error rather than quietly accepting it.
Key takeaways
ifruns a block when its condition istrue;elseruns a block when it isfalse.- Exactly one of the two branches runs.
elsehas no condition and always pairs with anif.- Conditions must be
Booleanin Kotlin. if (...) a else bcan also be used as a value.