Kotlin 的“when”语句 vs Java 中的“switch”
任何编程语言中的 switch-case 语句都允许程序员针对不同的值对它进行测试。它还提供了一个选项,在变量的值与给定值不匹配时执行某些操作。在本文中,我们将采用一个简单的示例,演示如何在 Kotlin 中实现 switch-case 语句。
Kotlin 不提供编写 switch-case 语句的任何选项。但是,Kotlin 提供了一个实现 when() 的选项,它的工作方式与其他编程语言中的 switch 完全相同。
示例 - 在 Java 中实现 switch-case
在此示例中,我们将在 Java 中实现 switch-case。
public class MyExample {
public static void main(String[] args) {
int number=10;
switch(number){
case 10: System.out.println("Input was 10");
break;
case 20: System.out.println("Input was 20");
break;
case 30: System.out.println("Input was 30");
break;
// Default case statement
default:System.out.println("Input was not 10, 20 or 30");
}
}
}输出
它将产生以下输出 −
Input was 10
示例 - 使用 when() 实现 switch-case
在此示例中,我们将生成一个随机值,并将使用 when() 对变量执行不同的操作。
fun main(args: Array<String>) {
// generating random value for our variable 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 -> { // Note the block
print("x is neither 1 nor 2")
}
}
}输出
执行时,它将在 1 到 10 之间生成一个随机值。
Current value: 7 randomVal == 7
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP