Java-17 - switch case - 应删除未使用的方法参数

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

我有一个简单的方法,它接受一个枚举和 returns 一个字符串:

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;
    };
}

但是 Sonar 给我这个主要错误:Unused method parameters should be removed

如您所见,开关中使用了参数类型。有关详细信息,当我使用旧开关盒时一切正常。

关于这个问题的任何想法,声纳是否涵盖新的 Java 语法?


嗯,我注意到当我移除 default -> null; 声纳时正确!这很奇怪。

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;
    };
}

这不是错误,Sonar 正确地评估了如果列表 详尽 switch-expression 永远不会落入 default 分支。

另一方面,如果您决定不列出所有可能的枚举常量,则必须声明 default 分支。否则,代码将不可编译,因为要求每个枚举常量都可以匹配。

注意:您的代码包含 switch 表达式,而不是 switch 语句。

从技术上讲,语法 default -> null; 不是“参数”。 JLS refers to various components within a switch block as a "rule", "label", or "expression"; while the relevant JEP 也使用术语“从句”。

无论您如何称呼它的组件,Switch Expressions 都不同于旧的 Switch Statements。特别是,Switch 表达式 详尽.

来自 JEP,

Exhaustiveness

The cases of a switch expression must be exhaustive; for all possible values there must be a matching switch label. (Obviously switch statements are not required to be exhaustive.)

In practice this normally means that a default clause is required; however, in the case of an enum switch expression that covers all known constants, a default clause is inserted by the compiler to indicate that the enum definition has changed between compile-time and runtime. Relying on this implicit default clause insertion makes for more robust code; now when code is recompiled, the compiler checks that all cases are explicitly handled. Had the developer inserted an explicit default clause (as is the case today) a possible error will have been hidden.

Sonar 足够聪明,可以知道何时涵盖了所有基础,使默认子句不仅无法访问,而且会干扰上述行为。