Destructuring
- Kotlin course
- Intermediate
- Lesson 17/116
- 5 min
Learn componentN and destructuring declarations.
componentN and destructuring
Data classes generate a componentN method per property: component1, component2 and so on. These methods, with a destructuring declaration, split properties into separate variables.
Example: val (x, y) = point. This line calls point.component1() and point.component2(), assigning the results to x and y. Standard classes like Pair and Triple support this pattern too. In loops it appears as for ((k, v) in map).
Destructuring in loops
Destructuring can be used in a for loop too. This is convenient to split the items of a list.
Example: for ((name, age) in users) { println("$name - $age") }. Each item in users is split into two components. List, Pair and Map.Entry support this pattern. You can skip a component with _: val (name, _) = user.
Practice Destructuring with the Point data class
Define a data class named Point with a primary constructor taking val x: Int, val y: Int. In main create a Point(3, 4) instance and split it into a and b with destructuring. Print a and b separately with println.
Starter code
// Define the Point data class
// with x and y properties
// instantiate, split with destructuring
// print a and bSample solution
data class Point(val x: Int, val y: Int)
fun main() {
val p = Point(3, 4)
val (a, b) = p
println(a)
println(b)
}Expected output
3 4
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does <code>val (a, b) = point</code> do?
- It splits point into a and b and errors out
- It calls point.component1() and component2() and assigns to a and b Correct answer
- It deletes point
- It copies a and b into point
Explanation: destructuring calls componentN methods.
2 Match the destructuring patterns
| Term | Meaning |
|---|---|
val (x, y) = p |
Split into two |
component1() |
First property |
val (n, _) |
Skip the second |
for ((k, v) in m) |
Split in a loop |
3 Complete the destructuring declaration
val p = Point(3, 4)
val ____ = p
println(a)
println(b)
val p = Point(3, 4)
val (a, b) = p
println(a)
println(b)
Explanation: (a, b) splits into two components.