为记录定义默认构造函数

huangapple go评论117阅读模式
英文:

Define default constructor for record

问题

我有一个记录,并希望为它添加默认构造函数。

public record Record(int recordId) {
   public Record {
       
   }
}

但它创建了一个带有 int 参数的构造函数。

public final class Record extends java.lang.Record {
    private final int recordId;
    public Record(int);
    //other method
}

我们如何为记录添加默认构造函数?

英文:

I have a record and want to add default constructor to it.

public record Record(int recordId) {
   public Record {
       
   }
}

But it created constructor with int param.

public final class Record extends java.lang.Record {
    private final int recordId;
    public Record(int);
    //other method
}

How can we add a default constructor to a record?

答案1

得分: 62

分毛病的话,你无法定义一个默认构造函数,因为当没有构造函数被定义时,编译器会生成一个默认构造函数,因此任何被定义的构造函数都不符合默认构造函数的定义。

如果你想让一个记录拥有一个无参构造函数,记录允许添加额外的构造函数或工厂方法,只要那个将所有记录字段作为参数的“规范构造函数”被调用。

public record Record(int recordId) {
   public Record() {
      this(0); 
   }
}
英文:

To split hairs, you cannot ever define a default constructor, because a default constructor is generated by the compiler when there are no constructors defined, thus any defined constructor is by definition not a default one.

If you want a record to have a no-arg constructor, records do allow adding extra constructors or factory methods, as long as the "canonical constructor" that takes all of the record fields as arguments is called.

public record Record(int recordId) {
   public Record() {
      this(0); 
   }
}

答案2

得分: 30

显式构造函数

在您的情况下,您可以显式地指定一个无参构造函数,通过委托给带有默认值的规范构造函数,如果您希望的话,可以这样做 -

public Record(){
    this(Integer.MIN_VALUE);
}

简而言之,任何非规范构造函数都应该委托给一个规范构造函数,并且这对于这些表示的数据携带性质来说应该是成立的。

紧凑构造函数

另一方面,请注意您在代码中使用的表示方式。

public Record {}

被称为"紧凑构造函数",它表示一个接受所有参数的构造函数,也可以用于验证作为记录属性提供的数据。紧凑构造函数是声明规范构造函数的一种替代方式。

英文:

Explicit constructor

In your case, you can explicitly specify a no-argument constructor with the delegation to the canonical constructor with a default value if you want to and this can be done as -

public Record(){
    this(Integer.MIN_VALUE);
}

In short, any non-canonical constructor should delegate to one, and that should hold true for the data-carrying nature of these representations.

Compact Constructor

On the other hand, note that the representation you had used in your code.

public Record {}

is termed as a "compact constructor" which represents a constructor accepting all arguments and that can also be used for validating the data provided as attributes of the record. A compact constructor is an alternate way of declaring the canonical constructor.

huangapple
  • 本文由 发表于 2020年4月11日 13:02:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/61152337.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定