Nam*_*man 3 java arity java-record java-16
尝试使用record和记录组件的一些代码。我正在使用变量 rarity 组件,并且在自定义构造函数上遇到了编译时错误。
public record Break<R extends Record>(R record, String... notifications) {
public Break(R record, String... notifications) {
System.out.println("record: " + record + " and notifications: " + Arrays.toString(notifications));
this.record = record;
this.notifications = notifications;
}
// compile error: non canonical record constructor must delegate to another costructor
public Break(R record) {
System.out.println("record: " + record);
this.record = record;
}
public Break() {
this(null); // this works
// actually intelliJ suggests it uses the constructor that is not compiling
}
public static void main(String[] args) {
new Break<>(new Break<>());
}
}
Run Code Online (Sandbox Code Playgroud)
我很好奇的是,当通过另一个自定义构造函数调用而没有为初始化提供任何组件时,如何推断类似的构造函数。
这与可变数量无关。所有记录构造函数链都必须在规范构造函数(可以使用紧凑形式指定)中“触底反弹”,变量数量与否。这表现为要求每个非规范构造函数必须委托给另一个构造函数;最终这意味着链在规范中触底。
您可以使用以下方法修复错误的构造函数:
public Break(R record) {
this(record);
}
Run Code Online (Sandbox Code Playgroud)
但是,您甚至不需要全部声明这个构造函数,因为规范构造函数new Break(r)已经可以处理表单的调用了。
| 归档时间: |
|
| 查看次数: |
246 次 |
| 最近记录: |