Hanbit the Developer

Kotlin Documentation | Destructuring declarations 본문

Kotlin

Kotlin Documentation | Destructuring declarations

hanbikan 2023. 5. 22. 16:41

Kotlin Documentation 시리즈에 대해

Category: Concepts

문서 링크: https://kotlinlang.org/docs/destructuring-declarations.html


val (name, age) = person

위 코드는 아래 코드로 컴파일된다.

val name = person.component1()
val age = person.component2()

for문에서도 적용된다.

for ((key, value) in map) {
   // do something with the key and the value
}

Underscore for unused variables

val (_, status) = getResult()

Destructuring in lambdas

{ a -> ... } // one parameter
{ a, b -> ... } // two parameters
{ (a, b) -> ... } // a destructured pair
{ (a, b), c -> ... } // a destructured pair and another parameter

타입 명시:

map.mapValues { (_, value): Map.Entry<Int, String> -> "$value!" }

map.mapValues { (_, value: String) -> "$value!" }