Kotlin when:超強大的 switch
如果你覺得 Java 的 switch-case 很難用(忘記寫 break 還會穿透),那你一定會愛上 Kotlin 的 when。
when 既可以取代 switch,也可以當作更強大的 if-else if 鏈。
基本用法 (取代 switch)
val x = 1
when (x) {
1 -> println("x is 1")
2 -> println("x is 2")
else -> { // 對應 Java 的 default
println("x is neither 1 nor 2")
}
}
不需要寫
break,它不會自動穿透 (Drop-through)。組合條件
多個條件執行同一件事,用逗號 , 分隔。
when (x) {
0, 1 -> println("x == 0 or x == 1")
else -> println("otherwise")
}
範圍與型別檢測
when 的強大之處在於它可以用表達式當條件,不只是常數。
val x = 10
val validNumbers = 1..10
when (x) {
in 1..10 -> println("x is in the range") // 檢查範圍
in validNumbers -> println("x is valid")
!in 10..20 -> println("x is outside the range")
is String -> println("x is a String") // 檢查型別
else -> println("none of the above")
}
當作表達式使用
跟 if 一樣,when 也可以有回傳值。
val text = when (x) {
1 -> "One"
2 -> "Two"
else -> "Unknown"
}
else -> "Unknown"
}
無參數的 when
這是 if-else if-else 的最佳替代品。程式碼會乾淨非常多。
when {
x.isOdd() -> print("x is odd")
x.isEven() -> print("x is even")
else -> print("x is funny")
}