코틀린의 해체 선언 사용법

해체 선언(Destructuring Declaration)은 코틀린에서 객체를 여러 변수로 분해하는 편리한 문법 기능입니다. 이는 복합 값을 한 번에 여러 속성으로 추출하고 각각의 변수에 할당할 수 있게 합니다.

기본 해체 선언

기본적인 해체 선언 문법은 다음과 같습니다:

val (fullName, years) = individual

이는 다음과 동일합니다:

val fullName = individual.component1()
val years = individual.component2()

데이터 클래스와 해체 선언

데이터 클래스는 자동으로 componentN() 함수가 생성되기 때문에 해체 선언을 지원합니다:

data class Individual(val fullName: String, val years: Int)

fun main() {
    val individual = Individual("Alice", 25)
    val (fullName, years) = individual
    println("$fullName is $years years old") // 출력: Alice is 25 years old
}

컬렉션에서의 해체 선언

해체 선언은 컬렉션에서도 사용 가능합니다:

val items = listOf(1, 2, 3)
val (x, y, z) = items
println("$x, $y, $z") // 출력: 1, 2, 3

맵과 함께 사용되는 해체 선언

맵 항목 처리 시 특히 유용합니다:

val peopleAges = mapOf("Alice" to 25, "Bob" to 30)

for ((name, age) in peopleAges) {
    println("$name is $age years old")
}

필요하지 않은 값 무시하기

필요하지 않은 값을 언더스코어 _ 를 사용하여 무시할 수 있습니다:

val (nameOnly, _) = individual // 오직 이름만 해체하고 나이는 무시

사용자 정의 해체 선언

데이터 클래스가 아닌 경우, 직접 componentN() 연산자 함수를 정의할 수 있습니다:

class Individual(val fullName: String, val years: Int) {
    operator fun component1() = fullName
    operator fun component2() = years
}

fun main() {
    val individual = Individual("Bob", 30)
    val (fullName, years) = individual
    println("$fullName is $years years old") // 출력: Bob is 30 years old
}

람다 표현식에서의 해체 선언

람다 매개변수에서 해체 선언을 사용할 수 있습니다:

peopleAges.mapValues { (key, value) -> "$key -> $value" }

하나의 매개변수만 필요하다면 이렇게 작성할 수 있습니다:

peopleAges.mapValues { (_, value) -> "value is $value" }

함수 반환값의 해체 선언

함수는 Pair 또는 Triple을 반환하고 이를 해체할 수 있습니다:

fun getDetails() = Pair("Alice", 25)

val (name, age) = getDetails()

중첩된 해체 선언

중첩된 해체 선언도 가능합니다:

data class Name(val firstName: String, val lastName: String)
data class Individual(val name: Name, val years: Int)

fun main() {
    val individual = Individual(Name("Alice", "Smith"), 25)
    val ((first, last), years) = individual
    println("$first $last is $years years old")
}

해체 선언의 제한 사항

  1. 해체 변수의 수는 componentN() 함수의 수와 일치해야 합니다.
  2. 해체 변수의 이름은 사용자가 지정할 수 없으며, component1(), component2() 등의 순서대로 대응됩니다.

태그: Kotlin data-class destructuring-declaration map pair

7월 12일 23:56에 게시됨