Conditionals
if produces a value directly in Kotlin, replacing the ternary operator entirely, and when is a far more flexible switch that can test arbitrary conditions.
if as an expression
In Kotlin, if can produce a value directly — there's no separate ternary operator because if/else already does the job:
fun main() {
val score = 82
val grade = if (score >= 90) "A" else if (score >= 80) "B" else "C"
println(grade)
}
B
Every branch of the if must produce a value of a compatible type for this to work as an expression — the compiler enforces that else is present, since a missing branch would leave the expression with no value in that case.
when: a more powerful switch
when replaces Java's switch, but it's an expression too, and its branches can be arbitrary conditions, not just exact matches:
fun main() {
val hour = 14
val period = when {
hour < 12 -> "Morning"
hour < 17 -> "Afternoon"
else -> "Evening"
}
println(period)
}
Afternoon
Used without an argument like this, each branch is its own boolean condition, checked top to bottom — the first one that's true wins. when can also match against a single value directly, closer to a traditional switch, with when (hour) { 9, 10, 11 -> ...; else -> ... }.