S131 false positive for enhanced switch merged statements

  • Operating system: Windows 10
  • SonarLint plugin version: 7.1.1.54565
  • Programming language you’re coding in: java
  • Is connected mode used:
    • 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()

2 Likes

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.

Or just don’t have a duplicate branch?

Either:

    switch (pos) {
      case THIRD -> doSomethingElse();
      default -> doSomething();
    }

Or:

    switch (pos) {
      case FIRST, SECOND -> doSomething();
      case THIRD -> doSomethingElse();
      default -> { /* Ignore */ }
    }
1 Like

Yes, that are also valid options. Thanks.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.