Kotlin Powerful when
when
One of the interesting feature is when.
“when” clause is very powerful feature.
In other language, switch is similar feature.
But, when is more powerful.
switch like
fun useWhen(x : Any?) { when(x) { 1 -> print("x == 1") 2 -> print("x == 2") else -> { print("x is not 1 or 2") } } }
x is Any type, we can use number, string, object etc…
It looks like switch, but in this case, we can use not only number.
Use with range
fun useWhen(x : Any?) { when(x) { in 1..10 -> print("1 to 10") } }
Like if else
fun useWhen(obj: Any): String = when(obj) { 1 -> "One" "Hello" -> "Greeting" is Long -> "Long" !is String -> "Not a String" else -> "Unknown" }
enum
Of course, we can use it with enum
Enums.kt
enum class ProtocolState { StateA, StateB, StateC}
Main.kt
fun useWhen2(protocol : ProtocolState) { when(protocol) { ProtocolState.StateA -> println("StateA") ProtocolState.StateB -> println("StateB") else -> println("StateC") } }