Connected to SonarCloud or SonarQube (and which version): SonarQube Enterprise Edition Version 9.5
Thorough description of the problem / question:
When using enhanced switch with merged statements, SonarLint in IntelliJ Idea (with or without connected mode - doesn’t matter) raises an issue java:S131 for the following example:
public enum Position {
FIRST,
SECOND,
THIRD
}
public class TestClass {
public void testMethod(Position pos) {
switch (pos) {
case FIRST, SECOND -> doSomething();
case THIRD -> doSomethingElse();
}
}
}
where in the next example, there is no issue (except the fact that two branches can be merged):
public class TestClass {
public void testMethod(Position pos) {
switch (pos) {
case FIRST -> doSomething();
case SECOND -> doSomething();
case THIRD -> doSomethingElse();
}
}
}
I don’t know which sonar products may be impacted except SonarLint and SonarQube.
I think this is intended behavior, since if a new enum value is added this code will not do anything and you won’t notice.
Notice that if you do this instead, you no longer get the warning
var result = switch (pos) {
case FIRST, SECOND -> doSomething();
case THIRD -> doSomethingElse();
};
This is because now that the switch is required to provide a result for all possible branches, you will receive a compile-time error if you add a new enum value but forget to add a corresponding branch.
But if you really want to, you can make this warning go away by explicitly declaring default -> doNothing()
Thank you for the reply.
In my case doSomething() and doSomethingElse() are void methods, and by providing the default branch the IDE starts complaining that there are duplicate branches.
I guess I have no other choice but to suppress either the IDE or Sonar warning then.