原文: https://beginnersbook.com/2019/02/kotlin-when-expression/

Kotlin 中的when表达与 CC++Java 等其他编程语言中的switch-case相同。**

Kotlin when表达式的简单的例子

  1. /**
  2. * created by Chaitanya for Beginnersbook.com
  3. */
  4. package beginnersbook
  5. fun main(args : Array<String>){
  6. var ch = 'A'
  7. when(ch){
  8. 'A' -> println("A is a Vowel")
  9. 'E' -> println("E is a Vowel")
  10. 'I' -> println("I is a Vowel")
  11. 'O' -> println("O is a Vowel")
  12. 'U' -> println("U is a Vowel")
  13. else -> println("$ch is a Consonant")
  14. }
  15. }

输出:

  1. A is a Vowel

我们也可以用更清洁的方式重写相同的代码,如下所示:

  1. /**
  2. * created by Chaitanya for Beginnersbook.com
  3. */
  4. package beginnersbook
  5. fun main(args : Array<String>){
  6. var ch = 'A'
  7. when(ch){
  8. 'A', 'E', 'I', 'O', 'U' -> println("$ch is a Vowel")
  9. else -> println("$ch is a Consonant")
  10. }
  11. }

Kotlin when表达式的范围

我们也可以在when中使用范围。在下面的示例中,我们在when表达式中使用了多个范围来查找给定数字中的数字。

  1. /**
  2. * created by Chaitanya for Beginnersbook.com
  3. */
  4. package beginnersbook
  5. fun main(args : Array<String>){
  6. var num = 78
  7. when(num) {
  8. in 1..9 -> println("$num is a single digit number")
  9. in 10..99 -> println("$num is a two digit number")
  10. in 100..999 -> println("$num is a three digit number")
  11. else -> println("$num has more than three digits")
  12. }
  13. }

输出:

Kotlin `when`表达式 - 图1

表达式里面的算术运算

我们还可以对我们在when表达式中传递的变量执行操作。

  1. /**
  2. * created by Chaitanya for Beginnersbook.com
  3. */
  4. package beginnersbook
  5. fun main(args : Array<String>){
  6. var age = 16
  7. when(age) {
  8. in 1..17 -> {
  9. val num = 18 - age
  10. println("You will be eligible for voting in $num years")
  11. }
  12. in 18..100 -> println("You are eligible for voting")
  13. }
  14. }

输出:

Kotlin `when`表达式 - 图2