- Language: Java
- Rule: java:S6916 “Use when instead of a single if inside a pattern match body”
- Running SonarLint SonarLint 10.1.0.81817 under eclipse 2024-03 (4.31)
The rule marks the contents of case CONSTANT_A below as non-compliant, suggesting replacing the if with a guard clause (“when”).
As per JLS §14.11.1, guard clauses can only be used for case patterns, and not for case constants, thus this is a false positive.
public class Test {
private static final int CONSTANT_A = 1, CONSTANT_B = 2;
public static void method(final int toSwitch, final boolean toCheck) {
switch(toSwitch) {
case CONSTANT_A -> {
if(toCheck) // FP raised here
System.out.println("it's A and true");
}
case CONSTANT_B -> {
if(toCheck) // No warning here, as expected
System.out.println("it's B and true");
else
System.out.println("it's B and false");
}
default -> System.out.println("it's neither");
}
}
}