如何在 Kotlin 中实现 switch-case 语句?


任何编程语言中的 switch-case 语句是一种选择控制机制,允许开发者测试变量或表达式的值并基于比较结果更改程序的控制流。它还提供了一个选项,当变量的值与给定值不匹配时进行某些操作。

Kotlin 不提供编写 switch-case 语句的选项;但是,我们可以使用 when() 函数在 Kotlin 中实现 switch-case 功能,其工作方式与其他编程语言中的 switch 完全相同。

在本文中,我们将举一个简单的例子并演示如何在 Kotlin 中实现 switch-case 功能。

示例——使用 when() 实现 Switch-Case

在此示例中,我们将生成一个随机值,并将使用 when() 对变量执行不同的操作。

fun main(args: Array<String>) {
   // generating a random value between 0 to 10
   var randomVal=(0..10).random()
   println("Current value: " + randomVal)
   when (randomVal) {
      1 -> print("randomVal == 1")
      2 -> print("randomVal == 2")
      3 -> print("randomVal == 3")
      4 -> print("randomVal == 4")
      5 -> print("randomVal == 5")
      6 -> print("randomVal == 6")
      7 -> print("randomVal == 7")
      8 -> print("randomVal == 8")
      9 -> print("randomVal == 9")
      10 -> print("randomVal == 10")
      else -> {
         print("x is neither 1 nor 2")
      }
   }
}

输出

输出可能因生成的随机值而异。

Current value: 10 
randomVal == 10

更新于: 16-Mar-2022

8K+ 浏览

开启您的 职业生涯

完成课程以获得认证

开始
广告
© . All rights reserved.