Destructuring Declarations
In this page:
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
fun main() {
val pair = "Kotlin" to 2011
val (language, year) = pair
println("$language was released in $year")
}
Login to try C/C++/Java/PHP code in the editor
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
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")
}
Login to try C/C++/Java/PHP code in the editor
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
fun main() {
val scores = mapOf("Ana" to 90, "Bo" to 85)
for ((name, score) in scores) {
println("$name scored $score")
}
}
Login to try C/C++/Java/PHP code in the editor
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
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")
}
Login to try C/C++/Java/PHP code in the editor
- Trying to destructure a regular class that has not declared
componentN()functions (or is not adata class), which the compiler rejects. - Assuming destructuring order is based on property names; it is actually based on declaration order via
component1(),component2(), etc. - Using
_unnecessarily verbosely instead of skipping an unwanted component with the underscore placeholder.
val (a, b) = pairdestructures an object into separate variables using itscomponent1(),component2(), etc. functions.- Data classes automatically provide
componentN()functions for their constructor properties, making them destructurable out of the box. PairandMap.Entryare 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: