if expression
- Kotlin course
- Beginner
- Lesson 38/116
- 5 min
Learn to use if as an expression in Kotlin.
The if expression
In Kotlin, if is not only a statement but also an expression. It can return a value. This replaces Java's ternary operator (?:).
val age = 20
val status = if (age >= 18) "Adult" else "Child"
println(status) // AdultWhen used as an expression, each branch must return a value and else is required. The value can be assigned to a variable or passed directly to a method.
This form is shorter and cleaner; it is preferred for simple two-way choices.
Practice Assign status with an if expression
Write a fun main(). Assign 20 to val age. Write val status = if (age >= 18) "Adult" else "Child". Print the result with println(status).
Starter code
fun main() {
// Use an if expression
}Sample solution
fun main() {
val age = 20
val status = if (age >= 18) "Adult" else "Child"
println(status)
}Expected output
Adult
Statement vs expression
It is important to distinguish the statement and expression forms of if. As a statement, it returns no value; it just runs a block.
// Statement: no value
if (x > 0) { println("Positive") }
// Expression: returns a value
val sign = if (x > 0) "+" else "-"In the expression form, branch types must match. if (x > 0) 1 else "a" is a compile error; one branch is Int, the other String.
Blocks can also return values: val r = if (x > 0) { compute() } else { 0 } — the last expression of the block is the value.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the else branch
val status = if (age >= 18) "Adult" ____ "Child"
val status = if (age >= 18) "Adult" else "Child"
Explanation: else gives the other branch's value in an if expression.
2 Match the if forms
| Term | Meaning |
|---|---|
if (x) { ... } |
Statement |
val s = if (x) a else b |
Expression |
else if |
Chain branch |
if without else |
Conditional block |
3 Why is else required in an if expression?
- Because each branch must return a value Correct answer
- For the curly braces
- No compile error otherwise
- For performance
Explanation: As an expression, each branch must produce a value; without else it is incomplete.