Kotlin If Else
The if...else statement lets your Kotlin program make decisions, and unlike in many other languages, it can also be used directly as an expression that produces a value.
The Basic if Statement
In Kotlin, the if statement executes a block of code only when a specified condition evaluates to true. The condition must be a Boolean expression, and unlike Java or C, Kotlin does not allow integers or other types to be used as a substitute for a Boolean condition.
Basic if
fun main() {
val temperature = 30
if (temperature > 25) {
println("It's a hot day")
}
}Adding else
The else branch runs when the if condition is false. Together, if and else let you cover both outcomes of a binary decision without repeating logic.
if...else
fun main() {
val age = 16
if (age >= 18) {
println("You can vote")
} else {
println("You cannot vote yet")
}
}Chaining with else if
When you need to test several conditions in sequence, chain else if clauses. Kotlin evaluates each condition from top to bottom and executes the first branch whose condition is true, skipping the rest.
- Conditions are checked in order, top to bottom.
- Only the first matching branch runs — the rest are skipped.
- The final else acts as a catch-all for anything not matched above.
else if chain
fun main() {
val score = 72
if (score >= 90) {
println("Grade: A")
} else if (score >= 75) {
println("Grade: B")
} else if (score >= 60) {
println("Grade: C")
} else {
println("Grade: F")
}
}if as an Expression
This is where Kotlin diverges from languages like Java. Because if is an expression, it can return a value directly, which you can assign to a variable or return from a function. When used this way, an else branch is required so that the expression always produces a value.
if as an expression
fun main() {
val a = 10
val b = 20
val max = if (a > b) a else b
println("The larger number is $max")
}Exercise: Kotlin If Else
Can an if/else block be used as an expression whose value is assigned to a variable?