gpt4 book ai didi

java - 为什么不使用自定义构造函数推断变量记录组件?

转载 作者:行者123 更新时间:2023-12-04 02:31:13 25 4
gpt4 key购买 nike

record 尝试一些代码并记录组件。我正在使用可变稀有组件,并在自定义构造函数上遇到编译时错误。

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<>());
}
}
我很想了解的是,在没有为初始化提供任何组件的情况下,通过另一个自定义构造函数调用类似的构造函数是如何推断的。

最佳答案

这与可变数量无关。所有记录构造函数链都必须在规范构造函数(可以使用紧凑形式指定)中“自下而上”,变量数量与否。这表现为每个非规范构造函数必须委托(delegate)给另一个构造函数的要求;最终这意味着链在规范中触底。
您可以使用以下方法修复错误的构造函数:

public Break(R record) {
this(record);
}
但是,您甚至不需要全部声明此构造函数,因为规范构造函数可以处理 new Break(r) 形式的调用。已经。

关于java - 为什么不使用自定义构造函数推断变量记录组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64131753/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com