1. 레코드클래스와 데이터클래스 비교 개요
| record (Java) | data (Kotlin) | |
| 목적 | Value 기반 타입 | 보일러플레이트 제거 |
| 성격 | 불변 데이터 운반자 (data carrier) | 편의 기능이 추가된 일반 클래스 |
| 불변 | 모든 필드 final | var / val 선택 |
| 상속 | 불가 | 가능 |
| 예시 | DTO Value Object 도메인 이벤트 |
상태가 바뀌는 모델 Value Object |
즉,
- Record class 는 "값 그 자체"를 표현하기 위한 "타입"
- Data class는 공통 편의 기능을 자동생성해주는 "일반 클래스"
2 . Data Class
fun main() {
val dto1 = PersonDto("홍길동", 100)
val dto2 = PersonDto("김길동", 110)
println(dto1)
println(dto2)
}
data class PersonDto(
val name: String,
val age: Int
)
- DTO(Data Transfer Object) 는
계층 간 데이터 전달을 목적으로 사용하는 객체이다. - 또한 data class를 사용하면
equals, hashCode, toString을 자동으로 제공받을 수 있어
DTO 구현 시 불필요한 보일러플레이트 코드를 작성할 필요가 없다. - Kotlin에서는 named argument를 활용하면 객체 생성 시 가독성이 높아져
Builder 패턴을 사용하는 것과 유사한 효과를 얻을 수 있다.
▶ data class + named argument = 최소 코드 + 높은 가독성
2 . Record Class
□ 일반 클래스와 Record 클래스 비교
1) 레코드 클래스
record Rectangle(double length, double width) { }
2) 1)과 동일한 일반 클래스
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() {...}
}
□ record 선언만으로 아래 요소들을 자동 생성
- the appropriate accessors
- (canonical) constructor
- equals / hashCode / toString
※ 주의할 점
record는 보일러플레이트 제거 효과를 제공하긴 하지만, 그 자체가 목적은 아니다.
record의 핵심 의도는 값 기반(value-based) 객체를 명확하고 안전하게 표현하는 타입을 만드는 것이다.
2) 생성자
- canonical constructor
: record의 모든 컴포넌트를 파라미터로 받는 생성자
: 컴포넌트 값에 대한 제어가 필요할 때 명시적 선언
record Rectangle(double length, double width) {
public Rectangle(double length, double width) {
if (length <= 0 || width <= 0) {
throw new java.lang.IllegalArgumentException(
String.format("Invalid dimensions: %f, %f", length, width));
}
this.length = length;
this.width = width;
}
}
- compact constructor
: 파라미터 선언을 생략한 생성자이며 값 검증에 용이.
record Rectangle(double length, double width) {
public Rectangle {
if (length <= 0 || width <= 0) {
throw new java.lang.IllegalArgumentException(
String.format("Invalid dimensions: %f, %f", length, width));
}
}
}
▶ 값을 바꾸거나 직접 할당하면 → Canonical constructor
단순히 조건만 검사하면 → Compact constructor
출처 : https://docs.oracle.com/en/java/javase/20/language/records.html
Java Language Updates
Record classes, which are a special kind of class, help to model plain data aggregates with less ceremony than normal classes.
docs.oracle.com
자바 개발자를 위한 코틀린 입문(Java to Kotlin Starter Guide)| 최태현 - 인프런 강의
현재 평점 5.0점 수강생 3,679명인 강의를 만나보세요. 이 강의를 통해 Kotlin 언어의 특성과 배경, 문법과 동작 원리, 사용 용례, Java와 Kotlin을 함께 사용할 때에 주의할 점 등을 배울 수 있습니다. Ko
www.inflearn.com
'JAVA > SPRING' 카테고리의 다른 글
| OAuth에서 JWT 토큰을 왜 쿠키와 Redis에 저장하나? (0) | 2025.12.25 |
|---|---|
| @MapsId : Derived Identifier (1) | 2025.12.22 |
| Null 안정성 확보 방법 (0) | 2025.12.19 |
| JPA 영속성(Persistence) 기초 정리 (1) | 2025.11.25 |
| 파일 업로드 (0) | 2025.11.23 |