【发布时间】:2021-05-05 19:20:37
【问题描述】:
最近我只是在创建另一个枚举类型。我利用了这样一个事实,即在 Java 中,枚举是一种特殊类型的类(而不是 named integer constant,就像在 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 关键字会为我保存此功能 was trying to save 我的样板代码。据我所知,这不与enums 结合使用。如果 enum records 已经存在,那么上述代码将如下所示:
enum record NamedIdentity(int id, String nickname) {
JOHN(1, "John the Slayer"),
JILL(2, "Jill the Archeress");
}
我的问题是:枚举记录 不存在有什么原因吗?我可以想象几个原因,包括但不限于:
- 此功能的用例数量太少,如果我们作为 Java 语言设计者设计和实现其他功能,Java 语言将受益更多。
- 由于枚举类型的内部实现,这很难实现。
- 我们作为 Java 语言设计者根本没有考虑到这一点,或者我们还没有收到社区这样的请求,所以我们没有优先考虑它。
- 此功能可能存在语义问题,或者此功能的实现可能会导致语义模糊或其他混乱。
【问题讨论】:
-
那么
NamedIdentity是否应该隐式扩展java.lang.Enum或java.lang.Record? -
记录与样板减少无关。事实上,这种记录的一个属性是以下代码返回 true:
original.equals(new NamedIdentitiy(original.id(), original.nickname()))。由于枚举没有公共构造函数,所以这段代码不能工作。 -
当您可以将
NamedIdentity定义为记录并在需要它们的地方声明static final NamedIdentity字段时,为什么还要使用枚举? -
@ayane 因为你可以切换枚举。
-
我可以向你保证,答案不是“我们没有考虑过这个。”
标签: java enums java-record