UseEnhancedSwitch
Since Checkstyle 13.3.0
Description
-> for case labels) is used
instead of the traditional switch (using : for case labels) where possible.
Rationale: Java 14 has introduced enhancements for switch statements and expressions
that disallow fall-through behavior. The enhanced switch syntax using ->
for case labels typically leads to more concise and readable code, reducing the likelihood
of errors associated with fall-through cases.
See the
Java Language Specification for more information about -> case labels, also known as
"switch rules".
Examples
To configure the check:
<module name="Checker">
<module name="TreeWalker">
<module name="UseEnhancedSwitch"/>
</module>
</module>
Example of violation:
public class Example1 {
void doSomething(String param) {
// method implementation
}
void t1(int x) {
// violation below, 'Switch can be replaced with enhanced switch'
switch (x) {
case 1:
doSomething("one");
break;
case 2:
doSomething("two");
break;
case 3:
doSomething("three");
break;
}
// ok, same as above but using enhanced switch
switch (x) {
case 1 -> doSomething("one");
case 2 -> doSomething("two");
case 3 -> doSomething("three");
}
// ok, switch with fall through is ignored
switch (x) {
case 1:
doSomething("one");
case 2:
doSomething("one or two");
break;
case 3:
doSomething("three");
break;
}
}
}
Example of violation with switch expression:
public class Example2 {
int switchExpressions(int x) {
// violation below, 'Switch can be replaced with enhanced switch'
int y = switch (x) {
case 1 : yield 1;
case 2 : yield 2;
case 3 : yield 3;
default: yield 0;
};
// ok, same as above but using enhanced switch
int yEnhanced = switch (x) {
case 1 -> 1;
case 2 -> 2;
case 3 -> 3;
default -> 0;
};
return y;
}
}
Example of Usage
Violation Messages
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
Package
com.puppycrawl.tools.checkstyle.checks.coding






