javaswitch-statementvoidjava-21

Java switch/case with arrow syntax and void statement


I want to translate the following classic Java switch/case code block into the new arrow syntax:

Classic:

switch (t) {
case A: foo1(); break;
case B: foo2(); break;
case C: break;
default: foo3(); break;
}

Arrow syntax (Java 21):

switch (t) {
case A -> foo1();
case B -> foo2();
case C -> ???; // void statement, what to place here?
default -> foo3();
}

Assuming the following:

public void foo1()
{
  // ...
}
public void foo2()
{
  // ...
}
public void foo3()
{
  // ...
}

and

enum TestEnum
{
  A,
  B,
  C
}

and

TestEnum t;

Unfortunately, it looks like the new syntax does not support empty or void statements. Just a ";" gives a syntax error.

Is there a clean way to achieve this, other than calling an empty noop-method or another fancy noop-statement like "".hashCode() for the "C"-case?


Solution

  • You can use an empty block:

    switch (t) {
    case A -> foo1();
    case B -> foo2();
    case C -> { /* do nothing */ }
    default -> foo3();
    }
    

    See also JEP 361: Switch Expressions and JLS 21: 14.11.1. Switch Blocks.

    Alternatively, you could also declare an empty method void doNothing() { } and call that.

    As an aside, depending on the problem you're solving, you may want to consider moving those methods to the enum instead (as an implementation per constant of an abstract method of the enum).