How to Use if as Expression in Kotlin: Simple Guide
In Kotlin,
if can be used as an expression that returns a value, allowing you to assign the result directly to a variable. This means you can write val result = if (condition) value1 else value2 to choose between values based on a condition.Syntax
The if expression in Kotlin evaluates a condition and returns a value based on that condition. It has the form:
if (condition) value1 else value2: returnsvalue1if the condition is true, otherwisevalue2.- The
elsepart is mandatory when usingifas an expression.
kotlin
val result = if (score >= 50) "Pass" else "Fail"
Example
This example shows how to use if as an expression to assign a message based on a number's value.
kotlin
fun main() {
val number = 7
val message = if (number % 2 == 0) {
"Even number"
} else {
"Odd number"
}
println(message)
}Output
Odd number
Common Pitfalls
One common mistake is forgetting the else branch when using if as an expression, which causes a compilation error. Another is using if as a statement when you want a value, leading to unexpected Unit results.
kotlin
/* Wrong: Missing else branch */ // val result = if (score > 0) "Positive" /* Right: Include else branch */ val result = if (score > 0) "Positive" else "Non-positive"
Quick Reference
| Usage | Description |
|---|---|
| if (condition) value1 else value2 | Returns value1 if condition is true, else value2 |
| val x = if (a > b) a else b | Assigns the greater of a or b to x |
| if used without else | Compilation error when used as expression |
| if as statement | Does not return a value, used for side effects |
Key Takeaways
Use if with else to return values as expressions in Kotlin.
Assign the result of if expression directly to variables for concise code.
Always include else branch when using if as an expression to avoid errors.
if expressions can have blocks with multiple statements inside braces.
Using if as a statement does not return a value and is different from expression usage.