In most languages if is a statement: it directs control and produces nothing. In Kotlin it is an expression that evaluates to a value, so it can sit on the right of an assignment. That is why Kotlin has no ternary operator - it does not need one, because if already does that job with better readability.
when is the same idea applied to multi-way branching, and it is considerably more capable than a switch. A branch can match a literal, several literals at once, a range, a type, or an arbitrary boolean condition. Used as an expression it must be exhaustive, and the compiler enforces that - which becomes extremely powerful in level two when it meets sealed classes.
Ranges are first-class. 1..10 is a value you can iterate, test membership against with in, or step through. until excludes the upper bound, downTo counts backwards, and step changes the stride. Together with for, this covers the loops you would otherwise write by hand with an index variable and an off-by-one risk.
Note the absence of a traditional three-part for loop. Kotlin deliberately has no for (int i = 0; i < n; i++). Everything is expressed as iteration over a range or a collection, which removes a whole family of boundary bugs.
fun grade(score: Int): String = when {
score >= 90 -> "Excellent"
score >= 70 -> "Good"
score >= 50 -> "Pass"
else -> "Needs work"
}
fun main() {
// if is an expression, so it assigns directly
val mood = if (grade(85) == "Good") "pleased" else "thoughtful"
println(mood)
// when matching literals, ranges and conditions
for (n in 1..5) {
val label = when (n) {
1 -> "one"
2, 3 -> "a couple"
in 4..5 -> "a few"
else -> "many"
}
println("$n is $label")
}
// Ranges backwards and with a stride
for (n in 10 downTo 0 step 5) print("$n ") // 10 5 0
}
Discussion
No questions on this topic yet. Sign in to ask the first one.