Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle "-> empty" in Kotlins "when"

Tags:

kotlin

Lets assume the following when-statement:

when(a)
{
   x    -> doNothing()
   y    -> doSomething()
   else -> doSomethingElse()
}

Now i'm looking to eliminate the boilerplate-function "doNothing()", e.g.:

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?

Any better ideas? I can't just eliminate x -> completely, as that would lead to else -> doSthElse()

Edit: directly after writing this Question, i figured out a possible answer x -> Unit. Any shortcomings with that?

like image 717
m.reiter Avatar asked Sep 07 '25 02:09

m.reiter


1 Answers

Kotlin has two existing possibilities to express a "do nothing" construct in when statements. Either Unit or an empty pair of braces. An empty block will just execute nothing. There's nothing else planned in that regard (see here).

To answer your question regarding "also, what is this actually doing?" for the empty block, looking at the bytecode and translating it into Java helps:

val x = 33
when(x)
{
    1 -> {}
    2 -> Int
    3 -> Unit
    else -> Double
}

Translates to

int x = 33;
switch(x) {
  case 1:
  case 3:
     break;
  case 2:
     IntCompanionObject var10000 = IntCompanionObject.INSTANCE;
     break;
  default:
     DoubleCompanionObject var1 = DoubleCompanionObject.INSTANCE;
}
like image 95
peterulb Avatar answered Sep 09 '25 00:09

peterulb