liveBook · Manning

Destructuring declaration

As explained in Kotlin in Action, 2E

A destructuring declaration is Kotlin syntax that initializes multiple variables from the component values of an expression.

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

How Kotlin in Action, 2E covers it

How deep it goes
Explains syntax, loops, lambdas, componentN functions, ignored values, and positional refactoring risks.
Examples
Demonstrates Pair unpacking, map iteration, map forEach, and selective Person data-class destructuring.
What it assumes
Assumes basic Kotlin variables, functions, collections, loops, lambdas, and data classes.
What you can do after
Apply destructuring to pairs, maps, loops, lambdas, data classes, and custom classes with componentN functions.
How it connects
Connects destructuring with Pair, data classes, componentN functions, extension functions, map entries, and loops.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kotlin in Action, 2E. The section links point to the parts of the book it draws on.