如何在Kotlins“when”中处理“-> empty”

m.r*_*ter 3 kotlin

让我们假设以下 when 语句:

when(a)
{
   x    -> doNothing()
   y    -> doSomething()
   else -> doSomethingElse()
}
Run Code Online (Sandbox Code Playgroud)

现在我正在寻找消除样板功能“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?
Run Code Online (Sandbox Code Playgroud)

有什么更好的想法吗?我不能完全消除x ->,因为那会导致else -> doSthElse()

编辑:在写完这个问题之后,我想出了一个可能的答案x -> Unit。那有什么缺点吗?

pet*_*ulb 6

Kotlin 有两种现有的可能性来在 when 语句中表达“什么都不做”的结构。Unit 或一对空的大括号。空块不会执行任何操作。在这方面没有其他计划(请参阅此处)。

回答您关于“此外,这实际上在做什么?”的问题。对于空块,查看字节码并将其翻译成 Java 有助于:

val x = 33
when(x)
{
    1 -> {}
    2 -> Int
    3 -> Unit
    else -> Double
}
Run Code Online (Sandbox Code Playgroud)

翻译成

int x = 33;
switch(x) {
  case 1:
  case 3:
     break;
  case 2:
     IntCompanionObject var10000 = IntCompanionObject.INSTANCE;
     break;
  default:
     DoubleCompanionObject var1 = DoubleCompanionObject.INSTANCE;
}
Run Code Online (Sandbox Code Playgroud)

  • 很高兴知道 {} 和 Unit 不会创建任何奇怪的工件:) (4认同)