Control Flow
Control Flow
If Expression
In Kotlin, if is an expression, i.e. it returns a value. Therefore there is no ternary operator (condition ? then : else), because ordinary if works fine in this role.
// Traditional usage var max = a if (a < b) max = b // With else var max: Int if (a > b) { max = a } else { max = b } // As expression val max = if (a > b) a else b
if branches can be blocks, and the last expression is the value of a block:
val max = if (a > b) { print("Choose a") a } else { print("Choose b") b }
If you're using if as an expression rather than a statement (for example, returning its value or assigning it to a variable), the expression is required to have an else
branch.
See the