Destructuring Declaration (Kotlin)

Destructuring unpacks an object's components into several variables in one statement, like val (name, age) = user. It works with data classes, pairs, maps, and any type defining componentN() operators.

Kotlin

Writing val (a, b) = pair binds a and b to the object's first and second components. Data classes automatically provide component1(), component2(), etc. from their constructor properties, so destructuring 'just works' for them, as it does for Pair, Triple, and Map entries.

It's especially handy in loops: for ((key, value) in map) iterates entries while unpacking each into named variables. You can use _ to skip a component you don't need: val (_, age) = user.

Destructuring is positional, not by name — order matters and follows the declared property order. For your own classes, implement operator fun componentN() to opt in.

Syntax

val (name, age) = user
for ((k, v) in map) { ... }

Examples

Kotlin

data class Person(val name: String, val age: Int)
val (name, age) = Person("Ada", 36)
println("$name is $age")

Output:

Ada is 36

Learn it in a lesson

See also

Back to the Dictionary