Using SonarLint for Eclipse, version 12.2.1.84686, with a Java 17 project, I think I’m seeing a false positive for an issue that keeps getting flagged. I’m willing to accept that I could rewrite my code or maybe I’m missing something, but here’s a code sample and what its saying:
private void testCase(final int varA, final byte[] varB) {
final String tempVar = switch(varA) {
case 9000 -> {
yield switch(varB[0]) {
case 1 -> "1";
case 2 -> "2";
case 3 -> "3";
default -> throw new RuntimeException("asdf1");
};
}
case 9001 -> "1";
case 9002 -> "4";
default -> throw new RuntimeException("asdf2");
}
}
Thanks for reaching out and sharing the code snippets!
This actually looks like a true positive, as the code can be simplified a bit. When using the arrow syntax (->) in a switch expression, you don’t need to wrap the nested switch in a block with a yield statement if it’s the only expression being evaluated. You can just return the nested switch directly.
Here is the fixed and cleaned-up version of your snippet:
private static void testCase(final int varA, final byte[] varB) {
final String tempVar = switch(varA) {
case 9000 -> switch(varB[0]) {
case 1 -> "1";
case 2 -> "2";
case 3 -> "3";
default -> throw new RuntimeException("asdf1");
};
case 9001 -> "1";
case 9002 -> "4";
default -> throw new RuntimeException("asdf2");
};
}
That being said, I completely admit that the issue message from SonarLint could be much clearer here, and it definitely would be helpful if a quick-fix was proposed for simple cases like this to save you the headache.
I’ve raised a ticket for this improvement in our backlog so the team can look into clarifying the rule message and adding a quick-fix: Jira
Let me know if this clears things up or if the IDE still complains after trying this out!