1️⃣ 클래스 선언과 생성자
- Java
public class User {
private final String name;
private int age;
public User(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() { return name; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
}
- Kotlin
class User(
val name: String,
var age: Int
)
→ Kotlin은 생성자 선언과 필드 선언이 동시에 가능. val은 불변, var은 가변
2️⃣ Null 안정성
- Java
String name = null;
- Kotlin
val name: String? = null
val length = name?.length ?: 0
→ Kotlin은 ?, ?., ?: (Elvis 연산자)로 null 처리를 문법 수준에서 강제
3️⃣ Data 클래스
- Java
@Data
@AllArgsConstructor
public class UserDto {
private String name;
private int age;
}
- Kotiln
data class UserDto(
val name: String,
val age: Int
)
→ data class만 쓰면 toString, equals, copy 등 자동 생성됨
4️⃣ 조건문 (id, when)
- Kotiln
val message = when (status) {
200 -> "OK"
404 -> "Not Found"
else -> "Unknown"
}
→ when은 switch보다 더 강력하고 표현식으로 사용 가능
5️⃣ 의존성 주입
- Java
@RequiredArgsConstructor
@Service
public class UserService {
private final UserRepository userRepository;
}
- Kotiln
@Service
class UserService(
private val userRepository: UserRepository
)
→ 생성자 주입을 클래스 헤더에서 처리, 코드가 훨씬 간결
6️⃣ 예외 처리
- Java
try {
// 작업
} catch (Exception e) {
e.printStackTrace();
}
- Kotiln
try {
// 작업
} catch (e: Exception) {
e.printStackTrace()
}
→ throws 선언 필요 없음. 예외 타입 이름은 e: Exception
7️⃣ 요약 비교
| 개념 | Java | Kotlin |
| final | final | val |
| nullable | null 가능 | String? |
| safe call | if != null | ?. |
| default param | 오버로딩 | = 값 |
| static method | static | companion object |
| utility 클래스 | Utils.method() | object 선언 |
'SPRING' 카테고리의 다른 글
| [SPRING] @TransactionalEventListener (0) | 2025.05.13 |
|---|---|
| [SPRING] 트랜잭션(Transaction) (1) | 2025.05.09 |
| [SPRING] 조건 검색 개선 (인덱싱, 파티셔닝, 분리 조회) (3) | 2025.05.02 |
| [SPRING] 파티셔닝(Partitioning) (1) | 2025.05.02 |
| [SPRING] JPA로 테이블 객체 다루기 (2) | 2025.04.30 |