kotlin 的 when 语句学习笔记

时间:2025-03-19 08:15:24

kotlin 中 when 的基本使用方法

kotlin 中的 when 的基本使用方法与 Java 中的 switch 类似。
下面分别是用 Java 的 switch 和 kotlin 的 when 实现同一逻辑的代码。

// Java 代码
switch(x){
 case 1:
 	System.out.println("x is 1");
 break;
 case 2:
 	System.out.println("x is 2");
 break;
 case 3:
 	System.out.println("x is 3");
 break;
 default:
 System.out.println("default");	
}
//kotlin 代码
when(x){
1->print("x is 1")
2->print("x is 2")
3->print("x is 3")
else->print("else")
}

kotlin 中 when 拥有的一些特别的用法(是 Java 中 switch 没有的)

  1. 多个分支拥有相同的处理时可以放在一起。
when(x){
1->print("x is 1")
2,3->print("x is 2 or 3")
else->print("else")
}
  1. 可以用来代替 if-else 链。
when{
3>2->print("3>2 is true")
4>3->print("4>3 is true")
5>6->print("5>6 is true")
}

会执行第一个为真的布尔表达式对应的处理逻辑。