Search code examples
javasonarqubejava-17switch-expression

Java-17 - switch case - Unused method parameters should be removed


I have a simple method which takes an enum and returns a String:

public static String enumToString(MyEnum type) {
    return switch (type) {
        case Enum1 -> "String_1";
        case Enum2 -> "String_2";
        case Enum3 -> "String_3";
        case Enum4 -> "String_4";
        case Enum5 -> "String_5";
        case Enum6 -> "String_6";
        default -> null;
    };
}

But Sonar gives me this Major error:Unused method parameters should be removed.

as you can see the parameter type is used in the switch. For more details when I use old switch case every thing is OK.

Any idea about the issue, does sonar cover new Java syntaxes?


Hmm, I notice that when I remove default -> null; sonar pass correctly! this is weird.

public static String enumToString(MyEnum type) {
    return switch (type) {
        case Enum1 -> "String_1";
        case Enum2 -> "String_2";
        case Enum3 -> "String_3";
        case Enum4 -> "String_4";
        case Enum5 -> "String_5";
        case Enum6 -> "String_6";
        //default -> null;
    };
}

Solution

  • This is not a bug, Sonar correctly evaluates that if the listing is exhaustive the switch-expression can never fall into the default branch.

    On the other hand, if you decide to not list all possible enum constants, the default branch, however, must be declared. Otherwise, the code would not be compilable, because of the requirement that every enum constant can be matched.

    Note: Your code contains a switch expression, not a switch statement.