Destructuring Declarations
Destructuring declarations let you decompose an object's properties into multiple variables at once.
Syntax
// Basic destructuring declaration
val (variable1, variable2) = object
// Destructuring declaration in a for loop
for ((variable1, variable2) in collection) { }
// Skip unwanted elements with an underscore
val (variable1, _, variable3) = object
Syntax overview
| Syntax | Description |
|---|---|
| val (a, b) = pair | Destructures a Pair or data class into multiple variables. |
| componentN() | The underlying functions that enable destructuring. Generated automatically for data classes. |
| val (k, v) = map.entries | Destructures map entries for iteration. |
| val (_, b) = pair | Uses an underscore to skip unwanted elements. |
Sample code
// data classes automatically have componentN() functions.
data class Point(val x: Int, val y: Int)
data class Person(val name: String, val age: Int, val city: String)
fun minMax(list: List<Int>): Pair<Int, Int> {
return Pair(list.min(), list.max())
}
fun main() {
// Destructuring a data class
val point = Point(10, 20)
val (x, y) = point
println("x=$x, y=$y") // x=10, y=20
// Skip unwanted elements.
val person = Person("Tanaka", 30, "Tokyo")
val (name, _, city) = person
println("$name lives in $city") // Tanaka lives in Tokyo
// Destructure the return value of a function.
val numbers = listOf(3, 1, 4, 1, 5, 9, 2)
val (min, max) = minMax(numbers)
println("min=$min, max=$max") // min=1, max=9
// Destructure map entries in a loop.
val scores = mapOf("Alice" to 90, "Bob" to 75)
for ((name2, score) in scores) {
println("$name2: $score points")
}
}
Details
Destructuring declarations work by calling component1(), component2(), and so on in order. data class generates these functions automatically, but for regular classes you need to define them yourself.
Pair and Triple also support destructuring, making them convenient to use with functions that return multiple values. The number of variables in a destructuring declaration cannot exceed the number of componentN() functions on the object — doing so causes a compile error.
If you find any errors or copyright issues, please contact us.