In Kotlin, if expressions are used for decision-making. Unlike some other programming languages, Kotlin’s if is an expression, meaning it returns a value. This makes it more versatile because it can be directly assigned to a variable or used in a function return.
Here’s how it works:
1. Basic if expression
The simplest usage is just like a usual if statement:
val number = 10
if (number > 0) {
println("$number is positive")
}
2. if-else expression
Kotlin’s if can be combined with else to define two branches of logic:
val number = -5
if (number > 0) {
println("$number is positive")
} else {
println("$number is non-positive")
}
3. Using if as an expression
The key feature of Kotlin’s if is that it returns a value. This means you can assign the result of an if to a variable:
val number = 15
val result = if (number % 2 == 0) {
"Even"
} else {
"Odd"
}
println("The number is $result")
Here, the value of result will be "Odd" because number is 15.
4. if with multiple branches
You can include more than two branches by chaining multiple else if conditions:
val number = 0
val result = if (number > 0) {
"Positive"
} else if (number < 0) {
"Negative"
} else {
"Zero"
}
println("The number is $result")
5. Returning block results
When using an if expression with blocks (multiple lines), the last expression in each block is the value that gets returned:
val a = 10
val b = 20
val max = if (a > b) {
println("a is greater")
a // This value is returned
} else {
println("b is greater")
b // This value is returned
}
println("Maximum is $max")
6. if as a shorthand
For simple conditions, you can write the if expression in a single line:
val age = 18
val isAdult = if (age >= 18) "Adult" else "Minor"
println("You are $isAdult")
In this case, there’s no need for curly braces.
Notes:
ifexpressions must always cover all cases when used to assign a result. If you omit theelsebranch and none of the conditions are met, the code will result in a compilation error.- For decision-making scenarios with many options, consider using
whenexpressions for more readability.
