if Expressions
In Kotlin, if can be used not only as a statement but also as an expression. You can assign the result of a conditional branch to a variable or return it directly from a function.
Syntax
// Basic form used as a statement.
if (condition) {
// process
} else if (condition) {
// process
} else {
// process
}
// Used as an expression (returns a value).
val variable = if (condition) valueA else valueB
Syntax List
| Syntax | Description |
|---|---|
| if (condition) | Executes the block when the condition is true. |
| else if (condition) | Evaluates an additional condition when the previous condition is false. |
| else | The block that runs when all conditions are false. |
| if expression | The last expression in the block is returned as the value. Use this instead of the ternary operator. |
Sample Code
fun main() {
val score = 75
// Basic if / else if / else.
if (score >= 90) {
println("Excellent.")
} else if (score >= 60) {
println("Pass.") // Prints "Pass."
} else {
println("Fail.")
}
// Assign to a variable using an if expression (instead of a ternary operator).
val result = if (score >= 60) "Pass" else "Fail"
println(result) // Prints "Pass"
// When using blocks, the last expression becomes the value.
val grade = if (score >= 90) {
println("Excellent!")
"A"
} else if (score >= 70) {
println("Good!") // Prints "Good!"
"B"
} else {
"C"
}
println(grade) // Prints "B"
// You can also use an if expression in a function return.
val x = 10
val abs = if (x >= 0) x else -x
println("Absolute value: $abs") // Prints "Absolute value: 10"
// Also useful for null checks.
val name: String? = "Kotlin"
val greeting = if (name != null) "Hello, $name" else "No name provided"
println(greeting) // Prints "Hello, Kotlin"
}
Notes
Kotlin does not have Java's ternary operator (? :). Instead, you can use if as an expression to achieve the same result. When using if as an expression, an else branch is always required. Without else, the value cannot be determined and a compile error will occur.
For branching on multiple conditions, the when expression is a better fit. The ?: Elvis operator is also handy when working with nullable types.
If you find any errors or copyright issues, please contact us.