Kotlin when code example
Example 1: kotlin when
fun numberTypeName(x: Number) = when(x) {
0 -> "Zero"
in 1..4 -> "Four or less"
5, 6, 7 -> "Five to seven"
is Byte -> "Byte"
else -> "Some number"
}
Example 2: kotlin when
fun signAsString(x: Int)= when {
x < 0 -> "Negative"
x == 0 -> "Zero"
else -> "Positive"
}
Example 3: Kotlin when
val x = 3
when(x) {
3 -> println("yes")
8 -> println("no")
else -> println("maybe")
}
val y = when(x) {
3 -> "yes"
8 -> "no"
else -> "maybe"
}
println(y)
Example 4: when kotlin
when (x) {
1 -> print("x == 1")
2 -> print("x == 2")
else -> {
print("x is neither 1 nor 2")
}
}
Example 5: kotlin if
if (a > b) {
max = a
} else {
max = b
}