如何在 Kotlin 中实现 switch-case 语句

227

如何在 Kotlin 中实现以下 Java switch 语句的等效代码?

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

2
你尝试过使用 when 表达式 吗? - Ray Toal
1
在 Kotlin 中没有 Switch 语句。您可以使用 When 语句。When 语句与 Switch 语句相同。 - Shohel Rana
10个回答

360

你可以这样做:

when (x) {
    1 -> print("x == 1")
    2 -> print("x == 2")
    else -> { // Note the block
        print("x is neither 1 nor 2")
    }
}
官方帮助中提取

如果有一个没有 break 语句的 switch 语句(或者只在几个地方),在 Kotlin 中应该如何编写? - Shadman Akhtar
Kotlin的when语句不支持穿透。你需要以根本不同的方式编写它。 - undefined

49
在Java中的switch语句,在Kotlin中相当于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
    }
}

这些大部分编译成 switch 语句,除了 when { ... },它会编译成一系列的 if 语句。

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

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


47

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

}

有助于处理多个情况/值的相同操作! - Virat18

22

When Expression

when replaces the switch operator of C-like languages. In the simplest form it looks like this

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

when matches its argument against all branches sequentially until some branch condition is satisfied. when can be used either as an expression or as a statement. If it is used as an expression, the value of the satisfied branch becomes the value of the overall expression. If it is used as a statement, the values of individual branches are ignored. (Just like with if, each branch can be a block, and its value is the value of the last expression in the block.)

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


16

当使用多个分支定义条件表达式时,可以使用if/else语句。它类似于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关键字。如果要创建循环,您可以像这样操作:

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
在Kotlin中,没有switch-case语句。但是我们有类似于switch的when表达式。就像if-else或switch一样,首先检查所有条件,如果没有匹配的条件,则评估else代码。
when (n) {
    1 -> {
        print("First")
        // run your code
    }
    2 -> print("Second")
    3, 4 -> print("Third or Forth") // check multiple conditions for same code
    in 1..100 -> print("Number is in the range")
    else -> {
        print("Undefined")
    }
}

在switch case中不需要任何休息。


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

2
以下是一个示例,了解如何使用“when”与任意对象: VehicleParts 是一个枚举类,有四种类型。 mix 是一个方法,接受两种 VehicleParts 类型的参数。 setOf(p1, p2) - 表达式可以产生任何对象。 setOf 是 Kotlin 标准库函数,用于创建包含对象的 Set。
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))

0

如果您想在 Kotlin 中使用 switch case(When)打印或打开多个活动,请使用以下代码。谢谢。

var dataMap: Map<String?, String?> = HashMap() var noteType: String? = ""

when (noteType) {
        "BIGTEXT" -> NEW_PAGE(dataMap)
        "NORMAL" -> NORMAL_PAGE(dataMap)
        "ABOUT"->ABOUT_PAGE((dataMap))

    }

不得不承认,我以为只是有多个活动的应用程序已经够糟糕了,结果发现你可以把它提升到另一个层次。 - JustSightseeing
我对我的代码进行了更正,请再次检查一下。 - Ankit Tiwari
@AnkitTiwari 他的意思是为不同大小的文本创建新页面是个坏主意,你需要使用 textSize 方法或类似的方法动态改变文本大小,而不是为此创建新的页面或活动。 - Acuna

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接