fun classify(n: Int): String = when {
n == 0 -> "zero"
n in 1..9 -> "single digit"
n in 10..99 -> "double digit"
n < 0 -> "negative"
n % 2 == 0 -> "even big number"
else -> "odd big number"
}
fun describe(x: Any): String = when (x) {
is Int -> "int $x"
is String -> "string of length ${x.length}" // smart cast to String here
is List<*> -> "list of ${x.size} items"
in 1..10 -> "small numberish" // works with operators
null -> "nothing"
else -> "unknown type ${x::class.simpleName}"
}
fun main() {
for (n in listOf(0, 5, 42, -3, 100, 7)) println("$n → ${classify(n)}")
for (x in listOf(7, "hi", listOf(1, 2, 3), null, 3.14)) println(describe(x))
}
Create a free account and build your private vault. Share publicly whenever you want.