【问题标题】:How to implement switch-case statement in Kotlin如何在 Kotlin 中实现 switch-case 语句
【发布时间】:2019-04-07 20:31:25
【问题描述】:

如何在 Kotlin 中实现等价于 Java switch 语句代码?

switch (5) {
    case 1:
    // Do code
    break;
    case 2:
    // Do code
    break;
    case 3:
    // Do code
    break;
}

【问题讨论】:

  • 你试过when expression吗?
  • Switch 语句在 Kotlin 中不可用。您可以使用When语句。When语句与Switch语句相同

标签: kotlin switch-statement


【解决方案1】:

你可以这样做:

when (x) {
    1 -> print("x == 1")
    2 -> print("x == 2")
    else -> { // Note the block
        print("x is neither 1 nor 2")
    }
}

摘自official help

【讨论】:

    【解决方案2】:

    switch 在 Java 中实际上是 when 在 Kotlin 中。但是,语法是不同的。

    when(field){
        condition -> println("Single call");
        conditionalCall(field) -> {
            print("Blocks");
            println(" take multiple lines");
        }
        else -> {
            println("default");
        }
    }
    

    以下是不同用途的示例:

    // This is used in the example; this could obviously be any enum. 
    enum class SomeEnum{
        A, B, C
    }
    fun something(x: String, y: Int, z: SomeEnum) : Int{
        when(x){
            "something" -> {
                println("You get the idea")
            }
            else -> {
                println("`else` in Kotlin`when` blocks are `default` in Java `switch` blocks")
            }
        }
    
        when(y){
            1 -> println("This works with pretty much anything too")
            2 -> println("When blocks don't technically need the variable either.")
        }
    
        when {
            x.equals("something", true) -> println("These can also be used as shorter if-statements")
            x.equals("else", true) -> println("These call `equals` by default")
        }
    
        println("And, like with other blocks, you can add `return` in front to make it return values when conditions are met. ")
        return when(z){
            SomeEnum.A -> 0
            SomeEnum.B -> 1
            SomeEnum.C -> 2
        }
    }
    

    其中大部分编译为switch,除了when { ... },它编译为一系列if语句。

    但对于大多数用途,如果您使用when(field),它会编译为switch(field)

    但是,我确实想指出,switch(5) 带有一堆分支只是浪费时间。 5 总是 5。如果您使用switch、if 语句或任何其他逻辑运算符,您应该使用变量。我不确定代码是否只是一个随机示例,或者这是否是实际代码。我指出这一点,以防是后者。

    【讨论】:

      【解决方案3】:

      kotlin

      中的switch case非常灵活
      when(x){
      
          2 -> println("This is 2")
      
          3,4,5,6,7,8 -> println("When x is any number from 3,4,5,6,7,8")
      
          in 9..15 -> println("When x is something from 9 to 15")
      
          //if you want to perform some action
          in 20..25 -> {
                       val action = "Perform some action"
                       println(action)
          }
      
          else -> println("When x does not belong to any of the above case")
      
      }
      

      【讨论】:

      • 有助于对多个案例/值进行相同处理!
      【解决方案4】:

      当表达式

      when 替换了类 C 语言的 switch 运算符。最简单的形式是这样的

      when (x) {
          1 -> print("x == 1")
          2 -> print("x == 2")
          else -> { // Note the block
              print("x is neither 1 nor 2")
          }
      }
      

      when 按顺序将其参数与所有分支匹配,直到满足某个分支条件。 when 可以用作表达式或语句。如果用作表达式,则满足分支的值成为整体表达式的值。如果将其用作语句,则忽略各个分支的值。 (就像if一样,每个分支都可以是一个块,它的值是块中最后一个表达式的值。)

      来自https://kotlinlang.org/docs/reference/control-flow.html#when-expression

      【讨论】:

        【解决方案5】:

        只需使用 when 关键字。如果你想制作一个循环,你可以这样做:

        var option = ""
        var num = ""
        
            while(option != "3") {
                println("Choose one of the options below:\n" +
                        "1 - Hello World\n" +
                        "2 - Your number\n" +
                        "3 - Exit")
        
                option = readLine().toString()
        
        // equivalent to switch case in Java //
        
                when (option) {
                    "1" -> {
                        println("Hello World!\n")
                    }
                    "2" -> {
                        println("Enter a number: ")
                        num = readLine().toString()
        
                        println("Your number is: " + num + "\n")
                    }
                    "3" -> {
                        println("\nClosing program...")
                    }
                    else -> {
                        println("\nInvalid option!\n")
                    }
                }
            }
        

        【讨论】:

          【解决方案6】:
                  val operator = '+'
                  val a = 6
                  val b = 8
          
                  val res = when (operator) {
                      '+' -> a + b
                      '-' -> a - b
                      '*' -> a * b
                      '/' -> a / b
                      else -> 0
                  }
                  println(res);
          

          常见情况我们使用下面的代码

                  val operator = '+'
                  val a = 6
                  val b = 8
          
                  val res = when (operator) {
                      '+',
                      '-' -> a - b
                      '*',
                      '/' -> a / b
                      else -> 0
                  }
                  println(res);
          

          【讨论】:

            【解决方案7】:

            when 定义具有多个分支的条件表达式。它类似于类 C 语言中的 switch 语句。它的简单形式如下所示。

               when (x) {
                1 -> print("x == 1")
                2 -> print("x == 2")
                else -> { // Note the block
                    print("x is neither 1 nor 2")
                }
            }
            

            when 将其参数依次匹配所有分支,直到满足某个分支条件。

            when 可以用作表达式或语句。如果用作表达式,则第一个匹配分支的值成为整个表达式的值。如果将其用作语句,则忽略各个分支的值。就像 if 一样,每个分支都可以是一个块,它的值就是块中最后一个表达式的值。

             import java.util.*
            
            fun main(args: Array<String>){
                println("Hello World");
            
                println("Calculator App");
            
                val scan=Scanner(System.`in`);
            
                println("""
                    please choose Your Selection to perform
                    press 1 for addition
                    press 2 for substraction
                    press 3 for multipication
                    press 4 for divider
                    press 5 for divisible
                    """);
            
                val opt:Int=scan.nextInt();
            
                println("Enter first Value");
                val v1=scan.nextInt();
                println("Enter Second Value");
                val v2=scan.nextInt();
            
                when(opt){
            
                    1->{
                        println(sum(v1,v2));
                    }
            
                    2->{
                        println(sub(v1,v2));
                    }
            
                    3->{
                        println(mul(v1,v2));
                    }
            
                    4->{
                        println(quotient(v1,v2));
                    }
            
                    5->{
                        println(reminder(v1,v2));
                    }
            
                    else->{
                        println("Wrong Input");
                    }
            
                }
            
            
            }
            
            
            fun sum(n1:Int,n2:Int):Int{
                return n1+n2;
            }
            
            fun sub(n1:Int, n2:Int):Int{
                return n1-n2;
            }
            
            fun mul(n1:Int ,n2:Int):Int{
                return n1*n2;
            }
            
            fun quotient(n1:Int, n2:Int):Int{
                return n1/n2;
            }
            
            fun reminder(n1:Int, n2:Int):Int{
                return n1%n2;
            }
            

            【讨论】:

              【解决方案8】:

              这里有一个例子来了解对任意对象使用“when”,

              VehicleParts是一个枚举类,有四种类型。

              mix 是一个接受两种 VehicleParts 类的方法。

              setOf(p1, p2) - 表达式可以产生任何对象

              setOf 是一个 kotlin 标准库函数,用于创建包含对象的 Set。

              集合是一个集合,其中项目的顺序无关紧要。 Kotlin 允许组合不同的类型来获得多个值。

              当我通过 VehicleParts.TWO 和 VehicleParts.WHEEL 时,我得到“自行车”。 当我通过 VehicleParts.FOUR 和 VehicleParts.WHEEL 时,我得到“汽车”。

              示例代码,

              enum class VehicleParts {
              TWO, WHEEL, FOUR, MULTI
              }
              
              fun mix(p1: VehicleParts, p2: VehicleParts) =
              when (setOf(p1, p2)) {
              
                  setOf(VehicleParts.TWO, VehicleParts.WHEEL) -> "Bicycle"
              
                  setOf(VehicleParts.FOUR, VehicleParts.WHEEL) -> "Car"
              
                  setOf(VehicleParts.MULTI, VehicleParts.WHEEL) -> "Train"
                  else -> throw Exception("Dirty Parts")
              
              }
              
              println(mix(VehicleParts.TWO,VehicleParts.WHEEL))
              

              【讨论】:

                猜你喜欢
                • 2012-12-13
                • 1970-01-01
                • 2017-08-26
                • 2013-09-24
                • 1970-01-01
                • 2014-08-05
                • 1970-01-01
                • 2021-06-13
                相关资源
                最近更新 更多