如何在 Kotlin 中实现以下 Java switch
语句的等效代码?
switch (5) {
case 1:
// Do code
break;
case 2:
// Do code
break;
case 3:
// Do code
break;
}
如何在 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")
}
}
从官方帮助中提取break
语句的 switch 语句(或者只在几个地方),在 Kotlin 中应该如何编写? - Shadman Akhtarwhen
语句不支持穿透。你需要以根本不同的方式编写它。 - undefinedswitch
语句,在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 语句或任何其他逻辑运算符,您应该使用变量。我不确定代码是随机示例还是实际代码。我在这里指出这一点,以防后者。
在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")
}
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 withif
, 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。
当使用多个分支定义条件表达式时,可以使用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;
}
只需使用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")
}
}
}
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中不需要任何休息。
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);
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))
如果您想在 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))
}
textSize
方法或类似的方法动态改变文本大小,而不是为此创建新的页面或活动。 - Acuna