Kotlin supports the usual logical conditions from mathematics. You can use these conditions to perform different actions for different decisions.
if to specify a block of code to be executed, if a specified condition is trueelse to specify a block of code to be executed, if the same condition is falseelse if to specify a new condition to test, if the first condition is false
fun main() {
val time = 20
if (time < 18) {
println("Good day.")
} else {
println("Good evening.")
}
}
In Kotlin, if can also be used as an expression (it returns a value). This allows you to assign the result of an if-statement directly to a variable.
fun main() {
val time = 20
val greeting = if (time < 18) "Good day." else "Good evening."
println(greeting)
}
Note: When using
ifas an expression, it must have anelsebranch.