Destructuring declarations allow you to "unpack" an object into variables right in the declaration, making the code concise. Historically, in Java and other languages, you had to write a separate getter for each component, which made the syntax bulky. Kotlin introduced special componentN() methods to support destructuring.
Problem: It's inconvenient to manually extract parts of a composite object — a lot of assignments are required, making the code less readable.
Solution: A data class automatically gets componentN() methods during compilation, allowing destructuring declarations to be used to retrieve property values.
Code example:
data class User(val name: String, val age: Int) val user = User("Pavel", 32) val (name, age) = user println("$name is $age years old") // Pavel is 32 years old
Key features:
How many variables can be obtained through destructuring declaration?
As many as there are componentN() methods defined in the class. For data classes, they are automatically created for all properties of the primary constructor (up to 255).
Does destructuring work with regular (non-data) classes?
Only if componentN() methods are declared manually in the class.
Example:
class Point(val x: Int, val y: Int) { operator fun component1() = x operator fun component2() = y } val (x, y) = Point(10, 20)
Can you skip values in a destructuring declaration?
Yes, use _ (underscore) to skip external variables.
val (_, onlyAge) = user
Negative case
In a project, a developer tried to use destructuring for a regular class without componentN() methods, which led to a compilation error; then they manually added them for a very large class (10+ properties).
Pros:
Cons:
Positive case
Using a data class with a limited number of parameters (for example, Result(val data: T, val error: Throwable?)), with concise destructuring declaration when processing a response in an API.
Pros:
Cons: