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

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)

我很好奇的是,当通过另一个自定义构造函数调用而没有为初始化提供任何组件时,如何推断类似的构造函数。

Bri*_*etz 5

这与可变数量无关。所有记录构造函数链都必须在规范构造函数(可以使用紧凑形式指定)中“触底反弹”,变量数量与否。这表现为要求每个非规范构造函数必须委托给另一个构造函数;最终这意味着链在规范中触底。

您可以使用以下方法修复错误的构造函数:

public Break(R record) {
    this(record);
}
Run Code Online (Sandbox Code Playgroud)

但是,您甚至不需要全部声明这个构造函数,因为规范构造函数new Break(r)已经可以处理表单的调用了。

  • @JohannesKuhn 我同意当前的定义可能会排除一些(同意:罕见)在语义上仍然是候选者的情况。在更罕见的情况下,性能差异实际上可能很重要(但我怀疑这种情况非常罕见)。但仅凭这一点仍然不足以得出我们选择了错误的规则集的结论;选择规则涉及平衡许多不同的考虑因素,这只是其中之一。设计涉及权衡;在这里,我们排除了一些可能的好案例,以排除更多的坏案例。问我5年后我们是否做对了...... (2认同)