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

问题描述

使用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<>());
    }
}

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

解决方法

这与可变arity无关。所有记录构造函数链必须在规范构造函数(可以使用紧凑形式指定)中“自下而上”(无论是否可变变量)。这体现为每个非规范构造函数都必须委托给另一个构造函数的要求。最终,这意味着链条在规范处触底。

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

public Break(R record) {
    this(record);
}

但是,由于规范的构造函数已经可以处理new Break(r)形式的调用,所以您甚至不需要全部声明该构造函数。