作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
empty"中处理 "when"-6ren"> empty"中处理 "when"-让我们假设以下 when 语句: when(a) { x -> doNothing() y -> doSomething() else -> doSomethingEls-6ren">
让我们假设以下 when 语句:
when(a)
{
x -> doNothing()
y -> doSomething()
else -> doSomethingElse()
}
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/
我是一名优秀的程序员,十分优秀!