Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Kotlin中实现switch-case语句_Kotlin_Switch Statement - Fatal编程技术网

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

如何在Kotlin中实现switch-case语句,kotlin,switch-statement,Kotlin,Switch Statement,如何在Kotlin中实现以下Javaswitch语句代码的等价物 switch (5) { case 1: // Do code break; case 2: // Do code break; case 3: // Do code break; } 你可以这样做: when (x) { 1 -> print("x == 1") 2 -> print("x == 2") else -&g

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

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

你可以这样做:

when (x) {
    1 -> print("x == 1")
    2 -> print("x == 2")
    else -> { // Note the block
        print("x is neither 1 nor 2")
    }
}
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")
            }
        }
    }
摘自

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

when (x) {
    1 -> print("x == 1")
    2 -> print("x == 2")
    else -> { // Note the block
        print("x is neither 1 nor 2")
    }
}
按顺序将其参数与所有分支匹配,直到满足某个分支条件
when
可用作表达式或语句。如果将其用作表达式,则满足的分支的值将成为整个表达式的值。如果将其用作语句,则忽略各个分支的值。(就像使用
if
一样,每个分支都可以是一个块,其值是块中最后一个表达式的值。)


当Kotlin中的
时,Java中的From

开关
实际上是
。但是,语法是不同的

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
    }
}
除了编译成一系列if语句的
when{…}
之外,大多数代码都编译成
switch

但对于大多数用途,如果您在(字段)
时使用
,它将编译为
开关(字段)


然而,我想指出的是,带有大量分支的
开关(5)
只是浪费时间。5永远是5。如果使用
开关
、If语句或任何其他逻辑运算符,则应使用变量。我不确定这段代码是一个随机的例子,还是实际的代码。如果是后者,我会指出这一点。

开关盒在kotlin中非常灵活

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

}

下面是一个使用“when”处理任意对象的示例

VehicleParts是一个包含四种类型的枚举类

mix是一种接受两种类型车辆部件类的方法

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

setOf是一个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))

只需使用when关键字即可。如果要进行循环,可以执行以下操作:

when (x) {
    1 -> print("x == 1")
    2 -> print("x == 2")
    else -> { // Note the block
        print("x is neither 1 nor 2")
    }
}
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")
            }
        }
    }
对于常见情况,我们使用以下代码

        val operator = '+'
        val a = 6
        val b = 8

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

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

   when (x) {
    1 -> print("x == 1")
    2 -> print("x == 2")
    else -> { // Note the block
        print("x is neither 1 nor 2")
    }
}
在满足某个分支条件之前,按顺序将其参数与所有分支匹配

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;
}
import java.util*
趣味主线(args:Array){
println(“你好世界”);
println(“计算器应用程序”);
val scan=扫描仪(系统中的'in`);
println(“”)
请选择要执行的选择
按1进行添加
按2键进行减法运算
按3键进行多重化
按4键进行分隔
按5键可除
""");
val opt:Int=scan.nextInt();
println(“输入第一个值”);
val v1=scan.nextInt();
println(“输入第二个值”);
val v2=scan.nextInt();
何时(选择){
1->{
println(和(v1,v2));
}
2->{
println(sub(v1,v2));
}
3->{
println(mul(v1,v2));
}
4->{
println(商(v1,v2));
}
5->{
println(提醒(v1,v2));
}
其他->{
println(“错误输入”);
}
}
}
乐趣和(n1:Int,n2:Int):Int{
返回n1+n2;
}
趣味潜水艇(n1:Int,n2:Int):Int{
返回n1-n2;
}
有趣的mul(n1:Int,n2:Int):Int{
返回n1*n2;
}
趣味商(n1:Int,n2:Int):Int{
返回n1/n2;
}
趣味提示(n1:Int,n2:Int):Int{
返回n1%n2;
}

您是否尝试过?切换语句在Kotlin中不可用。您可以使用When语句。When语句与Switch语句相同有助于对多个案例/值进行相同的处理!