본문 바로가기

프로그래밍/Java

[Java] 레코드(Record)

2021년 11월 21일에 작성된 글입니다.

레코드(Record)

변경할 수 없는 데이터의 투명한 전달자 역할을 하는 클래스

Kotlin의 data class와 비슷한 것이라고 보면 될 것 같다.

JDK 14에서 preview로 도입되었으며, JDK 16에서 정식으로 도입되었다.
JEP 395 Records

코드로 비교해보자

Before

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 메서드를 오버라이드 해주었다.

After

record Point(int x, int y) {}

record를 이용해서 이렇게 간결하게 작성할 수 있다.

'프로그래밍 > Java' 카테고리의 다른 글

[Java] JDK 버전별 차이점 정리 (1.5~17)  (2) 2024.09.04
[Java] Pattern Matching for instanceof  (0) 2024.09.04
[Java] Switch Expression  (0) 2024.09.04