Destructuring declarations in Kotlin allow you to "unpack" objects into their constituent parts directly in variable declarations, making code clearer and more concise.
By default destructuring works with data classes and is supported for collections (via component functions). It is based on the use of componentN() functions inside the object's class.
Example with a data class:
data class User(val name: String, val age: Int) val user = User("Oleg", 32) val (name, age) = user println(name) // "Oleg" println(age) // 32
Example for a custom class:
class Point(val x: Int, val y: Int) { operator fun component1() = x operator fun component2() = y } val point = Point(1, 2) val (a, b) = point
Details and nuances:
for ((k, v) in map), where k and v yield key/value pairs.Question: "Can you use destructuring for a class that is not a data class, and what are the requirements for that?"
Answer: Yes. You need to manually define operator componentN functions inside the class. A data class generates them automatically, but any class can provide them explicitly.
Example:
class Pair<A, B>(val first: A, val second: B) { operator fun component1() = first operator fun component2() = second } val p = Pair(1, "q") val (a, b) = p
Case
In a project they used destructuring with Map and mistakenly assumed destructuring is available for any iterable collections. As a result, "ComponentN is missing" errors occurred for List, where multiple components were expected but only one existed, which led to application crashes.
Case
In one module destructuring was applied to custom classes, but after refactoring they forgot to add operator
componentNfunctions; as a result the code compiled but threwNoSuchMethodErrorat runtime, bringing down the production service.
Case
A data class was modified — the attributes were reordered, but the old destructuring declarations were left unchanged. The result: values were assigned to the wrong variables, causing a serious business-logic bug in production.