Conditionals: if and else
Prerequisites: Operators
A conditional runs code only when a condition is true.
Real-world analogy: "If it's raining, take an umbrella; otherwise, wear sunglasses."
Syntax
if (condition) {
// runs when condition is true
} else if (otherCondition) {
// runs when the first was false and this one is true
} else {
// runs when none of the above were true
}
Example
fun main() {
val temperature = 18
if (temperature > 25) {
println("It's hot")
} else if (temperature > 15) {
println("It's pleasant")
} else {
println("It's cold")
}
}
Expected output
It's pleasant
Kotlin checks the conditions top to bottom and runs only the first branch that matches.
if is an expression
if produces a value, so it replaces the ternary operator found in
other languages:
fun main() {
val age = 20
val status = if (age >= 18) "adult" else "minor"
println(status)
val a = 7
val b = 12
val larger = if (a > b) a else b
println(larger)
}
adult
12
When if is used as an expression, the else branch is required — the
expression must always produce a value.
Common mistakes
- Forgetting the parentheses:
if age > 18doesn't compile. Writeif (age > 18). - Putting conditions in the wrong order.
if (score > 50)beforeif (score > 90)means the second can never run.
Practice
Store an age and print adult for 18 and over, teen for 13–17, and
child otherwise.
Show solution
fun main() {
val age = 15
if (age >= 18) {
println("adult")
} else if (age >= 13) {
println("teen")
} else {
println("child")
}
}
teen