← Back to Kotlin Course | Chapter 8: Collections | Lesson 6 of 7

Destructuring Declarations

Destructuring lets you unpack several values out of one object into separate named variables all in a single line.

Destructuring a Pair

The standard library's Pair type provides component1() and component2(), so it can be destructured directly into two separate variables.

Example: Destructuring a Pair

markup
fun main() {
    val pair = "Kotlin" to 2011
    val (language, year) = pair
    println("$language was released in $year")
}

Destructuring a Data Class

Because data classes automatically generate componentN() functions for their constructor properties, any data class instance can be destructured directly.

Example: Destructuring a Data Class

markup
data class Point(val x: Int, val y: Int)

fun main() {
    val point = Point(3, 4)
    val (x, y) = point
    println("x=$x, y=$y")
}

Destructuring in for Loops

Destructuring works naturally inside a for loop header, which is especially handy when iterating over a Map's entries as key-value pairs.

Example: Destructuring in for Loops

markup
fun main() {
    val scores = mapOf("Ana" to 90, "Bo" to 85)
    for ((name, score) in scores) {
        println("$name scored $score")
    }
}

Skipping Components with Underscore

When only some components of a destructured value are needed, _ can be used as a placeholder for the ones you want to ignore.

Example: Skipping Components with Underscore

markup
data class Point3D(val x: Int, val y: Int, val z: Int)

fun main() {
    val point = Point3D(1, 2, 3)
    val (x, _, z) = point
    println("x=$x, z=$z")
}
Common Mistakes
  1. Trying to destructure a regular class that has not declared componentN() functions (or is not a data class), which the compiler rejects.
  2. Assuming destructuring order is based on property names; it is actually based on declaration order via component1(), component2(), etc.
  3. Using _ unnecessarily verbosely instead of skipping an unwanted component with the underscore placeholder.
Chapter Summary
  • val (a, b) = pair destructures an object into separate variables using its component1(), component2(), etc. functions.
  • Data classes automatically provide componentN() functions for their constructor properties, making them destructurable out of the box.
  • Pair and Map.Entry are standard library types that already support destructuring.
  • An underscore _ can be used in place of a component you want to skip.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.