[Java] 레코드(Record)

윤석진·2021년 11월 21일
0
post-thumbnail

레코드(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를 이용해서 이렇게 간결하게 작성할 수 있다.

profile
공부하며 쓰는 블로그

0개의 댓글