consistency - conventional
Why is this an issue? How can I fix it? More InfoJava 21 has introduced enhancements to switch statements and expressions, allowing them to operate on any type, not just specific ones, as in previous versions. Furthermore, case labels have been upgraded to support patterns, providing an alternative to the previous restriction of only accepting constants.
// As of Java 21 String patternMatchSwitch(Object obj) { return switch (obj) { case String s -> String.format("String %s", s); case Integer i -> String.format("int %d", i); default -> obj.toString(); }; }
This allows to use the when
keyword to specify a condition for a case label, also called a guarded case label.
String guardedCaseSwitch(Object obj) { return switch (obj) { case String s when s.length() > 0 -> String.format("String %s", s); case Integer i when i > 0 -> String.format("int %d", i); default -> obj.toString(); }; }
This syntax is more readable and less error-prone than using an if statement inside the case block and should be preferred.
This rule reports an issue when a single if
statement is used inside a case block.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4