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

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 (동반 객체)

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 - 여러 작업 실행후 결과 반환

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 - 객체로 여러 작업

fun main() {
    val numbers = mutableListOf(1, 2, 3)
    
    with(numbers) {
        add(4)
        add(5)
        println("크기: $size")
    }
    
    println(numbers)  // [1, 2, 3, 4, 5]
}

오홍..
이런거보면 코틀린은 함수형 스타일이 많네

Kotlin 에서 컬렉션이 뭐지