False positive on java:S1120 with switch expression

Version information:

  • SonarQube 8.9.0.43852
  • Manually installed sonar-java-plugin-7.2.0.26923.jar to support Java 16

Wrong indentation is reported for switch expressions with blocks:

class Foo {
    int foo(String value) {
        return switch (value) {
            case "A" -> {
                yield 1;
            }

            case "B" -> {
                yield 2;
            }

            default -> {
                yield 3;
            }
        };
    }
}

Results in Make this line start after 8 spaces to indent the code consistently.
We have indentationLevel parameter for this rule set to 4.
The formatting of the code snippet is OK, in my opinion.
Even if someone disagreed, the reported value makes no sense,

There is no problem with switch expressions without blocks:

class Foo {
    int foo(String value) {
        return switch (value) {
            case "A" -> 1;
            case "B" -> 2;
            default -> 3;
        };
    }
}

Of course, this simple case can avoid blocks, but it might not be an option for more complex cases.

Hello @pdolezal and welcome to the community!

I did not reach the same conclusions as you, in my tests, the two code samples you provided are raising false positives. Still, I agree that both are looking fine (it’s the style is used in JEP-361) and I confirm that this rule is not dealing correctly with switch expressions.

Ticket created: SONARJAVA-4007. We will make sure to test the different cases when implementing the fix.

Thanks for taking the time to report this issue.
Best,
Quentin

1 Like

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