Why programs need decisions
People decide things based on conditions all day: if it rains, take an umbrella; if you are hungry, eat. A program does the same with an if statement. It runs a block of code only when a condition is true, and skips it otherwise.
val isRainy = true
if (isRainy) {
println("I bring an umbrella")
}
This prints I bring an umbrella. With val isRainy = false it prints nothing, because the block is skipped.
The syntax
if (condition) {
// statements to run when the condition is true
}
- The keyword
ifstarts the statement. - The condition goes in parentheses.
- The block goes between curly braces. Everything inside runs only when the condition is true. Indent it by four spaces so the structure is easy to see.
Boolean conditions
The condition must be a Boolean, a value that is either true or false. It can be a Boolean variable, as above, or the result of a comparison such as age >= 18 or name == "Ana".
Kotlin is strict about this. A number or a string is not a condition, and the compiler rejects it:
val x = 5
if (x) { // does not compile
println("yes")
}
error: condition type mismatch: inferred type is 'Int' but 'Boolean' was expected.
Write the comparison you mean instead, for example if (x > 0).
Adding else
An else block holds the code that runs when the condition is false. It takes no condition of its own, because it covers every case the if did not:
val isHungry = false
if (isHungry) {
println("I have breakfast")
} else {
println("I wait")
}
Exactly one of the two blocks runs, never both and never neither. The usual style puts } else { on one line, so the closing brace of the first block, the keyword and the opening brace of the second all sit together.
The exercise
The starter code declares val passed: Boolean = true. The lesson builds the statement in three steps.
- Write the
if. The variablepassedis already a Boolean, so it is the whole condition. Writingpassed == truewould work but adds nothing. Put it in parentheses and open the block with{. - Print the success message inside the block. The text
"Passed the test"goes in aprintlncall, so it appears only when the condition holds. - Add the
else. Close the first block and open the second on the same line with} else {, print"Failed"inside it and close it with}. Now the program answers whichever valuepassedhas.
val passed: Boolean = true
if (passed) {
println("Passed the test")
} else {
println("Failed")
}
With passed set to true, the output is Passed the test. Change the first line to false and it becomes Failed.
Checking more than two cases
When two outcomes are not enough, chain further conditions with else if. Kotlin tests them from the top and runs the first block whose condition is true; the rest are skipped:
val x = 5
if (x > 10) {
println("a")
} else if (x > 3) {
println("b")
} else {
println("c")
}
This prints b. Both x > 3 and the final else could apply to 5, but the chain stops at the first match. Order therefore matters: put the most specific condition first.
Kotlin specifics
In Kotlin, if is also an expression: it produces a value, so you can assign it. When used this way, the else is required, because the value has to exist in every case:
val x = 5
val size = if (x > 3) "big" else "small"
println(size) // big
Kotlin has no ternary ? : operator. This form takes its place. Without the else, val s = if (x > 3) "big" is a compile error: 'if' must have both main and 'else' branches when used as an expression.
Common mistakes
- Leaving out the parentheses. The condition always goes inside
( ). - Using a non-Boolean condition.
if (x)with anIntfails to compile. - Trusting indentation instead of braces. Braces are optional when the body is one statement, but then only the next statement belongs to the
if. Inif (x > 3)followed by two lines, only the first line is conditional, and the second runs every time, however it is indented. Braces remove the doubt. - Using
=for comparison. A single=assigns; use==to compare. - Putting a condition on
else.else (x > 3)is not valid. To test another condition, writeelse if (x > 3) { ... }.
Key takeaways
if (condition) { ... }runs its block only when the condition istrue.- The condition must be a
Boolean. else { ... }runs when the condition isfalse.- In Kotlin,
ifcan also produce a value, as long as it has anelse.