Part 04 / Topic 1 of 8
if/else: a statement, or an expression
An if used as a statement just picks a branch to run; nothing comes back from it. Kotlin also
lets you use the exact same if/else as an expression: the whole thing evaluates to a value,
which you can hand straight to a val.
val marks = 78
// statement form: runs a branch, produces nothing
if (marks >= 40) {
println("Statement form: pass")
} else {
println("Statement form: fail")
}
// expression form: the if/else itself is the value
val result = if (marks >= 40) "pass" else "fail"
println("Expression form: $result")
Statement form: pass
Expression form: pass
A chain of if/else if is still one expression, and the last line of whichever branch runs
becomes the value of the whole thing:
val grade = if (marks >= 90) {
"A"
} else if (marks >= 75) {
"B"
} else if (marks >= 40) {
"C"
} else {
"F"
}
println("Grade: $grade")
Grade: B
This is why Kotlin has no separate ternary operator (cond ? a : b from Java/C) — if/else as an
expression already does that job, and reads the same whether the branches are one line or ten.
🔍 Going deeper: the compiler enforces this directly.
if (marks >= 40) "pass"with noelsecompiles fine as a statement (the branch just runs, and nothing happens on failure), but the moment you try to store it in aval, it fails:error: 'if' must have both main and 'else' branches when used as an expression.An
ifwithoutelse, used as a statement, is really "maybe do this" — it has no sensible value for the case where the condition is false, so Kotlin simply won't let you treat it as one.
Full program: examples/01_if_as_expression.kt.
Done here? The practice set for Part 4 — including the solutions — is on the part page.