if as an Expression
In this page:
if as a Statement
The familiar form of if runs one block of code or another based on a condition, without producing any value itself -- this is how if behaves in many other languages.
Example: if as a Statement
fun main() {
val age = 20
if (age >= 18) {
println("You are an adult")
} else {
println("You are a minor")
}
}
Login to try C/C++/Java/PHP code in the editor
if as an Expression
Kotlin also lets if produce a value directly, where the last expression in each branch becomes the result. This lets you assign the outcome straight to a val.
Note: Using if as an expression avoids declaring a var just to be set inside each branch.
Example: if as an Expression
fun main() {
val age = 20
val status = if (age >= 18) "adult" else "minor"
println("Status: $status")
}
Login to try C/C++/Java/PHP code in the editor
Multi-Branch if Expressions
Chaining else if lets an if expression cover more than two outcomes, with the last matching branch's final line providing the resulting value.
Example: Multi-Branch if Expressions
fun main() {
val score = 85
val grade = if (score >= 90) "A"
else if (score >= 80) "B"
else if (score >= 70) "C"
else "F"
println("Grade: $grade")
}
Login to try C/C++/Java/PHP code in the editor
Block Bodies in if Expressions
Each branch of an if expression can be a multi-line block; the last statement inside that block becomes the value contributed by that branch.
Example: Block Bodies in if Expressions
fun main() {
val number = 7
val description = if (number % 2 == 0) {
val kind = "even"
"The number is $kind"
} else {
"The number is odd"
}
println(description)
}
Login to try C/C++/Java/PHP code in the editor
- Writing
ifonly as a statement out of old habit, then separately assigning a variable in each branch instead of using it as an expression. - Forgetting that an
ifused as an expression needs anelsebranch, or the compiler cannot guarantee a value in every case. - Putting side effects (like printing) inside an
ifexpression that is also supposed to return a clean value, mixing concerns.
- In Kotlin,
ifcan be used as a statement (to choose which block runs) or as an expression (to produce a value). - When used as an expression, every branch's last line is the value produced by that branch.
- An
ifexpression must have anelsebranch to guarantee it always produces a value. - Using
ifas an expression often eliminates the need for a separate mutable variable.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: