Is there any way to force an exhaustive check of all enum values when the switch branches call methods with void return type? It's quite ugly to hard-code a yield just to coax the compiler to demand exhaustiveness.
This is my current pattern (the handle methods have void return type)
int unused = switch (event.getEventType()) {
case ORDER -> { handle((OrderEvent) event); yield 0; }
case INVOICE -> { handle((InvoiceEvent) event); yield 0; }
case PAYMENT -> { handle((PaymentEvent) event); yield 0; }
};
The reason I want to use an expression is to get a compilation error when a new enum value is added and is not handled.
Maybe yield a
Consumer
ofEvent
, so you yield something useful, the trade off is one more line forconsumer.accept
.Continue if you concern performance
Based on the comment concerning performance penalty, a benchmark is performed to compare following scenarios:
To see
handle
method?And the result is:
By observing the result, there is no much different between the 4 scenarios.
handle
method is neglectable.The benchmark is performed with:
CPU: Intel(R) Core(TM) i7-8750H
Memory: 16G
JMH version: 1.19
VM version: JDK 15.0.2