empty"中处理 "when"-6ren"> empty"中处理 "when"-让我们假设以下 when 语句: when(a) { x -> doNothing() y -> doSomething() else -> doSomethingEls-6ren">
gpt4 book ai didi

kotlin - 如何在 Kotlins "-> empty"中处理 "when"

转载 作者:行者123 更新时间:2023-12-04 12:19:41 26 4
gpt4 key购买 nike

让我们假设以下 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com