변경할 수 없는 데이터의 투명한 전달자 역할을 하는 클래스
Kotlin의 data class
와 비슷한 것이라고 보면 될 것 같다.
JDK 14에서 preview로 도입되었으며, JDK 16에서 정식으로 도입되었다.
JEP 395 Records
class Point {
private final int x;
private final int y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
int x() { return x; }
int y() { return y; }
public boolean equals(Object o) {
if (!(o instanceof Point)) return false;
Point other = (Point) o;
return other.x == x && other.y == y;
}
public int hashCode() {
return Objects.hash(x, y);
}
public String toString() {
return String.format("Point[x=%d, y=%d]", x, y);
}
}
그동안은 단순 불변 데이터 저장용으로 클래스를 만들고, equals
, hashCode
, toString
메서드를 오버라이드 해주었다.
record Point(int x, int y) {}
record
를 이용해서 이렇게 간결하게 작성할 수 있다.