13

最近我只是在创建另一种枚举类型。我利用了这样一个事实,即在 Java 中,枚举是一种特殊类型的类(而不是像在 C# 中那样命名的整数常量)。我用两个字段制作了它,一个全参数构造函数和两个字段的 getter。

这是一个例子:

enum NamedIdentity {

    JOHN(1, "John the Slayer"),
    JILL(2, "Jill the Archeress");

    int id;
    String nickname;

    NamedIdentity(int id, String nickname) {
        this.id = id;
        this.nickname = nickname;
    }

    id id() {
        return this.id;
    }

    String nickname() {
        return this.nickname;
    }
}

然后我认为 Java 14 的record关键字会为我保存该功能试图拯救我的样板代码。据我所知,这不与enums 结合。如果存在枚举记录,则上述代码将如下所示:

enum record NamedIdentity(int id, String nickname) {
    JOHN(1, "John the Slayer"),
    JILL(2, "Jill the Archeress");
}

我的问题是:枚举记录不存在是否有原因?我可以想象几个原因,包括但不限于:

  • 此功能的用例数量太少,如果我们作为 Java 语言设计者设计和实现其他功能,Java 语言将受益更多。
  • 由于枚举类型的内部实现,这很难实现。
  • 我们作为 Java 语言的设计者,根本没有考虑到这一点,或者我们还没有收到社区这样的要求,所以我们没有优先考虑它。
  • 此功能会存在语义问题,或者此功能的实现可能会导致语义模糊或其他混乱。
4

1 回答 1

14
于 2021-02-01T18:54:45.240 回答