让我们假设以下 when 语句:
when(a)
{
x -> doNothing()
y -> doSomething()
else -> doSomethingElse()
}
现在我正在寻找消除样板功能“doNothing()”,例如:
x -> //doesn't compile
x -> null //Android Studio warning: Expression is unused
x -> {} //does work, but my corporate codestyle places each '{‘ in a new line, looking terrible
//also, what is this actually doing?
有什么更好的想法吗?
我不能只是消除
x ->
完全,因为这会导致 else -> doSthElse()
编辑:在写完这个问题之后,我想出了一个可能的答案
x -> Unit
.那有什么缺点吗?
最佳答案
Kotlin 有两种现有的可能性来在 when 语句中表达“什么都不做”的结构。 Unit 或一对空的大括号。一个空块将不执行任何操作。
在这方面没有其他计划(请参阅 here )。
回答您关于“此外,这实际上在做什么?”的问题。对于空块,查看字节码并将其翻译成 Java 有助于:
val x = 33
when(x)
{
1 -> {}
2 -> Int
3 -> Unit
else -> Double
}
翻译成
int x = 33;
switch(x) {
case 1:
case 3:
break;
case 2:
IntCompanionObject var10000 = IntCompanionObject.INSTANCE;
break;
default:
DoubleCompanionObject var1 = DoubleCompanionObject.INSTANCE;
}
关于kotlin - 如何在 Kotlins "-> empty"中处理 "when",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60755131/