美文网首页
Kotlin 中 switch 写法,用when代替

Kotlin 中 switch 写法,用when代替

作者: Bfmall | 来源:发表于2022-04-08 16:22 被阅读0次

在Kotlin 中并没有switch 操作符 , 取而代之的是when

java的写法:

      int i= 5;
      switch (i){
          case 5:
              System.out.print("5");
              break;
 
          case 4:
              System.out.print("4");
              break;
 
          case 3:
              System.out.print("3");
              break;
 
          case 2:
              System.out.print("2");
              break;
 
          case 1:
              System.out.print("1");
              break;
      }

Kotlin 写法:

        val i = 5
        when (i) {
            5 -> print("5")
 
            4 -> print("4")
 
            3 -> print("3")
 
            2 -> print("2")
 
            1 -> print("1")
        }

相关文章

网友评论

      本文标题:Kotlin 中 switch 写法,用when代替

      本文链接:https://www.haomeiwen.com/subject/dspysrtx.html