Kotlin If..Else
if lets your program make decisions: run some code only when a condition is true. Kotlin's if has one superpower compared with Java or C — it is an expression, so it can produce a value.
if, else if, else
fun main() {
val temperature = 27
if (temperature > 30) {
println("It's hot - stay hydrated")
} else if (temperature > 20) {
println("Nice and warm")
} else {
println("Bring a jacket")
}
}Nice and warm
Conditions are checked from top to bottom; the first one that is true wins and the rest are skipped. The else branch runs if nothing matched.
| Form | Use when |
|---|---|
if (c) { … } |
do something only when c is true |
if (c) { … } else { … } |
choose between two paths |
if … else if … else |
choose among several paths |
If a branch is a single statement, the braces are optional: if (isAdmin) println("Welcome, admin").
if as an expression
Because if returns the value of the branch that runs, you can assign it directly. This replaces the ? : ternary operator that Kotlin does not have.
fun main() {
val age = 15
val ticket = if (age < 18) "child" else "adult"
println("Ticket type: $ticket")
val a = 8
val b = 13
val max = if (a > b) a else b
println("Max: $max")
}Ticket type: child
Max: 13
When used as an expression, if must have an else — otherwise there would be no value when the condition is false:
fun main() {
val age = 15
val ticket = if (age < 18) "child"
println(ticket)
}File.kt:3:18: error: 'if' must have both main and 'else' branches when used as an expression.
Blocks as values
When a branch is a block, its last expression is the value. Earlier lines can do other work:
fun main() {
val total = 64.0
val shipping = if (total >= 50) {
println("Free shipping unlocked!")
0.0
} else {
println("Add ${50 - total} EUR for free shipping")
4.95
}
println("Shipping: $shipping")
}Free shipping unlocked!
Shipping: 0.0
Nested conditions
You can put an if inside another if, but deep nesting quickly becomes hard to read. Combining conditions with && / ||, or using when (next chapter), is often clearer.
fun main() {
val loggedIn = true
val role = "editor"
if (loggedIn) {
if (role == "admin") {
println("Full access")
} else {
println("Limited access for $role")
}
} else {
println("Please log in")
}
}Limited access for editor
Tip: Functions can use an
ifexpression as their whole body:fun sign(n: Int) = if (n >= 0) "+" else "-".
Test yourself
What is Kotlin's replacement for the ternary operator c ? a : b?
c ?: aif (c) a else bwhen (c) a b- There is none
What is printed? val n = 5; println(if (n % 2 == 0) "even" else "odd")
- even
- odd
- 5
- Compile error
When a branch of an if expression is a block, which value does it produce?
- The first expression
- The last expression in the block
- Unit always
- The value after
return