record class とは
特徴
- フィールドがイミュータブル(
private final
)- 一度インスタンス化した後に、値を変更できない
- 下記が自動的に作成される
- コンストラクタ
- getter
- equals
- hashCode
- toString
使い方
// クラス名の前にrecordをつける
record Rectangle(double length, double width) { }
下記の記述と同等
// record使わない場合
public final class Rectangle {
private final double length;
private final double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
double length() { return this.length; }
double width() { return this.width; }
// Implementation of equals() and hashCode(), which specify
// that two record objects are equal if they
// are of the same type and contain equal field values.
public boolean equals...
public int hashCode...
// An implementation of toString() that returns a string
// representation of all the record class's fields,
// including their names.
public String toString() {...}
}
使用場面
- 不変でシンプルなデータを持ちたい時
- 計算処理や状態遷移などを行わない時
参考