A destructuring declaration initializes multiple variables by unpacking the component values of one expression. It is useful when a function returns multiple values or when a composite value should be handled as separate local names. section 3.4.3 section 9.6
Unpack a Pair
val (number, name) = 1 to "one" The to function creates a Pair; the declaration assigns its first component to number and its second component to name. section 3.4.3
Destructuring follows component positions rather than variable names:
- Map entries expose component1 and component2, so loops can write for ((key, value) in map). section 9.4.1
- Lambdas can destructure composite values, including map entries, with map.forEach { (key, value) -> ... }. section 9.4.1
- Data classes support destructuring automatically; other classes can support it by defining componentN functions. section 9.6
- Use _ for an unused component, and omit trailing components when they are unnecessary. section 9.4.2
- Treat positional order as part of the contract: renaming variables does not change which component they receive, and property reordering can silently misassign values. section 9.4.2
Listing 9.16 Using a destructuring declaration to iterate over a map
fun printEntries(map: Map<String, String>) {
for ((key, value) in map) { #1
println("$key -> $value")
}
}
fun main() {
val map = mapOf("Oracle" to "Java", "JetBrains" to "Kotlin")
printEntries(map)
// Oracle -> Java
// JetBrains -> Kotlin
}
See a complete map-iteration example that prints each key-value pair using destructuring. section 9.4.1
