if as an Expression
Why Kotlin's if can produce a value directly, removing a whole category of temporary-variable boilerplate.
2 menit membaca
In many languages, if is purely a statement — it controls which block of code runs, but it doesn't produce a value itself. Kotlin's if can work that way too, but it can also be used as an expression, meaning the whole if/else evaluates to a value you can assign, return, or pass around directly.
The statement form
This should look familiar from most languages:
var max: Int
if (a > b) {
max = a
} else {
max = b
}It works, but it's more code than the logic deserves — two branches, each doing nothing but assigning to the same variable.
The expression form
Kotlin lets you skip the intermediate assignment entirely:
val max = if (a > b) a else bThe whole if/else evaluates to a single value — whichever branch's last expression matches the condition — and that value is assigned to max directly. When you use if this way, the else branch is required: without it, there's no guaranteed value for the compiler to use when the condition is false.
Multi-line branches
Each branch can be a block; the last expression in the block becomes that branch's value:
val message = if (score >= 90) {
val grade = "A"
"Excellent! Grade: $grade"
} else if (score >= 70) {
"Good job."
} else {
"Keep practicing."
}
println(message)Using if directly in a return
Because if produces a value, you can return it straight from a function without a temporary variable at all:
fun max(a: Int, b: Int): Int {
return if (a > b) a else b
}Combined with the single-expression function syntax you'll see later in this course, this becomes:
fun max(a: Int, b: Int) = if (a > b) a else bWhy this matters beyond brevity
This isn't just about typing fewer characters. When if is a statement, the compiler can't verify both branches produce a compatible value — that's on you to keep consistent by hand. When if is an expression, the compiler infers a single type for the whole expression from both branches, and it's a compile error if a branch is missing or the types don't line up. The shorter code is also the more strictly checked code.
Kotlin extends this same "control flow that produces a value" idea much further with when, covered next — its equivalent of a switch statement, but considerably more capable.