Code
kotlin
// Basic when
fun describe(n: Int): String = when {
n < 0 -> "negative"
n == 0 -> "zero"
n in 1..10 -> "small"
n in 11..100 -> "medium"
else -> "large"
}
println(describe(5))
// When on subject
fun type(x: Any): String = when (x) {
is Int -> "int ${x.toString()}"
is String -> "string len=${x.length}"
is List<*> -> "list size=${x.size}"
else -> "unknown"
}
println(type(42))
println(type("hello"))
println(type(listOf(1, 2)))
// When with enum
enum class Direction { NORTH, SOUTH, EAST, WEST }
fun arrow(d: Direction) = when (d) {
Direction.NORTH -> "^"
Direction.SOUTH -> "v"
Direction.EAST -> ">"
Direction.WEST -> "<"
}
println(arrow(Direction.NORTH))
// When as a statement with blocks
val v = 3
when (v) {
1, 2 -> println("one or two")
in 3..5 -> {
println("three to five")
println("handled")
}
else -> println("other")
}
// Branch returns value
val label = when (v % 2) {
0 -> "even"
else -> "odd"
}
println(label)