代码之家  ›  专栏  ›  技术社区  ›  Mayur Dabhi

如何在Kotlin中实现switch case

  •  0
  • Mayur Dabhi  · 技术社区  · 7 年前

    如何实现与以下Java等价的功能 switch Kotlin中的语句代码?

    switch (5) {
        case 1:
        // Do code
        break;
        case 2:
        // Do code
        break;
        case 3:
        // Do code
        break;
    }
    
    3 回复  |  直到 6 年前
        1
  •  244
  •   navylover    7 年前

    你可以这样做:

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

    摘自 official help

        2
  •  5
  •   Suresh B B    5 年前

    定义具有多个分支的条件表达式时。它类似于类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;
    }
    
        3
  •  29
  •   Zoe - Save the data dump 张群峰    7 年前

    switch 在Java中是有效的 when 在科特林。然而,语法是不同的。

    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
        }
    }
    

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

    when(field) ,编译成 switch(field) .

    然而,我想指出 switch(5) 有一堆树枝纯粹是浪费时间。5永远是5。如果你使用 转换 ,或if语句,或任何其他逻辑运算符,则应使用变量。我不确定这段代码是一个随机的例子,还是实际的代码。我要指出这一点,以防是后者。

        4
  •  21
  •   Watercayman    6 年前

    开关箱在使用中非常灵活 科特林

    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")
    
    }
    
        5
  •  3
  •   Diako Hasani    5 年前
            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);
    
        6
  •  7
  •   Grandtour p27    6 年前

    什么时候 关键词。如果你想做一个循环,你可以这样做:

    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")
                }
            }
        }
    
        7
  •  18
  •   Pang Ajmal PraveeN    5 年前

    当表达

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

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

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

    从…起 https://kotlinlang.org/docs/reference/control-flow.html#when-expression

        8
  •  1
  •   Manikandan    6 年前

    下面是一个使用任意对象的示例,

    车辆零件 是一个包含四种类型的枚举类。

    混合 是一个接受两种类型的VehiclePart类的方法。

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

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

    集合是指项目顺序无关紧要的集合。 Kotlin可以组合不同的类型以获得多个值。

    当我经过汽车零件时。两个和两个部分。轮子,我得到“自行车”。 当我经过汽车零件时。四和四部分。轮子,我有“车”。

    示例代码,

    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))