Background: Kotlin has supported the "destructuring" mechanism from the very beginning, allowing for convenient extraction of values from objects, collections, and return values of functions. This mechanism was inspired by languages like Scala and JavaScript (ES6 destructuring).
Problem: In classic OOP languages, extracting multiple properties from an object required either explicitly accessing each field or resorting to intermediate structures, resulting in verbosity. This is particularly inconvenient in loops, when processing pairs from a Map, or when working with data classes.
Solution: Destructuring declarations allow declaring multiple variables and assigning them values from an object in a single line, thanks to the implementation of component functions (componentN) in classes.
Code example:
data class Person(val name: String, val age: Int) val (n, a) = Person("Alex", 25) println("Name: $n, Age: $a") // Name: Alex, Age: 25 val map = mapOf(1 to "a", 2 to "b") for ((key, value) in map) println("$key = $value")
Key features:
Can any class be destructured?
No. ComponentN methods are required. Data classes and standard pairs/triples already contain them. For regular classes, they can be added manually.
Example:
class Point(val x: Int, val y: Int) { operator fun component1() = x operator fun component2() = y } val (cx, cy) = Point(5, 10)
What happens if you try to destructure an object with fewer componentN?
The compiler raises an error if you try to declare more variables than implemented componentN:
data class OnlyX(val x: Int) val (x, y) = OnlyX(5) // Error! No component2()
Is it possible to destructure a return value in a function?
Yes! A function can return a pair (Pair), a triplet (Triple), or a data class — destructuring supports this:
fun coords() = Pair(1, 2) val (x, y) = coords()
A data class with five fields is passed to a function; destructuring is used with five variables. Over time, a field was added — this pattern requires revisiting the entire logic of parsing, sometimes resulting in unused variables appearing.
Pros:
Cons:
Destructuring is used only for data classes with 2-3 fields (for example, x, y coordinates), or when iterating over a map, where the structure is guaranteed to be fixed.
Pros:
Cons: