3. Kotlin 기초 - 2
Class & Data Class
// 기본 클래스
class User(
val id: Long,
val name: String,
val email: String
) {
// 메서드
fun isVerified(): Boolean {
return email.endsWith("@daangn.com")
}
// 계산된 프로퍼티
val domain: String
get() = email.substringAfter("@")
}
fun main() {
val user = User(1, "Hope", "hope@daangn.com")
println(user.name) // Hope
println(user.isVerified()) // true
println(user.domain) // daangn.com
}
// DTO, 응답/요청 객체에 사용
data class Product(
val id: Long,
val title: String,
val price: Int,
val sellerId: Long
)
fun main() {
val product = Product(1, "아이폰", 1000000, 100)
// 1. toString() 자동 생성
println(product)
// Product(id=1, title=아이폰, price=1000000, sellerId=100)
// 2. copy() - 일부만 변경
val discounted = product.copy(price = 900000)
println(discounted)
// Product(id=1, title=아이폰, price=900000, sellerId=100)
// 3. equals() 자동 생성
val product2 = Product(1, "아이폰", 1000000, 100)
println(product == product2) // true (값으로 비교)
// 4. destructuring (구조 분해)
val (id, title, price, sellerId) = product
println("$title: ${price}원") // 아이폰: 1000000원
}
실전예시 - API 요청/응답 객체
// 요청 DTO
data class CreateProductRequest(
val title: String,
val price: Int,
val description: String,
val category: String
)
// 응답 DTO
data class ProductResponse(
val id: Long,
val title: String,
val price: Int,
val category: String,
val seller: SellerInfo,
val createdAt: String
) {
companion object {
// Entity → Response 변환
fun from(product: Product, seller: User): ProductResponse {
return ProductResponse(
id = product.id,
title = product.title,
price = product.price,
category = product.category,
seller = SellerInfo(seller.id, seller.name),
createdAt = product.createdAt.toString()
)
}
}
}
data class SellerInfo(
val id: Long,
val name: String
)
Scope Functions
- let - null 체크 & 변환
- let 은 "값이 null이면 이 코드 실행해줘"라는 뜻
- 옵셔널 체이닝과 비슷.
fun main(){
val email: String? = "hope@daangn.com"
email?.let(
println("이메일 길이: ${it.length}")
)
val userId: Long? = getCurrentuserId()
val user = userId?.let { id ->
userRepository.findById(id)
}
}
Compainon object (동반 객체)
- js의 static 메서드 와비슷.
- 객체 생성 로직 깔끔하게 분리
- 팩토리 패턴 구현
- 유틸함수 정의
data class User(
val id: Long,
val name: String
) {
companion object {
// 클래스 레벨 함수
fun fromJson(json: Map<String, Any>): User {
return User(
id = json["id"] as Long,
name = json["name"] as String
)
}
}
}
// 사용 - 클래스 이름으로 바로 호출
val user = User.fromJson(mapOf("id" to 1L, "name" to "Hope"))
Run - 여러 작업 실행후 결과 반환
- 객체가 null 일수 있을때
fun main() {
val result = "hope@daangn.com".run {
// this = "hope@daangn.com"
val domain = substringAfter("@")
val isCompany = domain == "daangn.com"
"도메인: $domain, 회사 이메일: $isCompany"
}
println(result)
// 도메인: daangn.com, 회사 이메일: true
}
With - 객체로 여러 작업
- 객체가 non-null일때
fun main() {
val numbers = mutableListOf(1, 2, 3)
with(numbers) {
add(4)
add(5)
println("크기: $size")
}
println(numbers) // [1, 2, 3, 4, 5]
}
오홍..
이런거보면 코틀린은 함수형 스타일이 많네
Kotlin 에서 컬렉션이 뭐지
- List, Set, Map 등을 통틀어서 부르는 말
- 그리고 이런 컬렉션을 다룰 때 함수형 메서드를 씀.