Quick Answer
Convenient way to extract multiple values at once
Understanding the Issue
Destructuring declarations allow you to unpack an object into multiple variables in one statement. Data classes automatically provide componentN() functions for destructuring.
The Problem
This code demonstrates the issue:
Kotlin
Error
// Problem: Manual property access
val person = Person("Alice", 30)
val name = person.name
val age = person.age
The Solution
Here's the corrected code:
Kotlin
Fixed
// Solution: Destructuring
val (name, age) = Person("Alice", 30)
// Also works with maps:
val map = mapOf("a" to 1, "b" to 2)
for ((key, value) in map) {
println("$key -> $value")
}
Key Takeaways
Use destructuring for cleaner code when working with compound values.