
Destructuring Declarations in Kotlin
📌 Destructuring Declarations in Kotlin
Destructuring Declarations in Kotlin allow you to unpack an object into multiple variables in a single statement. It simplifies code when working with data classes, collections, or custom objects.
✅ 1. Destructuring with Data Classes
In Kotlin, data classes automatically provide componentN()
functions (component1()
, component2()
, etc.) for destructuring.
📌 Example:
fun () { val user = User("Alice", 25) // Destructuring val (name, age) = user println("Name: $name") println(Name: AliceAge: 25
🔎 Explanation:
component1()
→ Extractsname
component2()
→ Extractsage
✅ 2. Destructuring in Functions
You can return a data class or a Pair/ Triple from a function and destructure it.
📌 Example using Data Class:
data class Person(val firstName: String, val lastName: String)fun (): Person { return Person("John", "Doe")}fun () { val (firstName, lastName) = getPerson() println("First Name: $firstName, Last Name: First Name: John, Last Name: Doe
📌 Example using Pair and Triple:
fun (): Pair<Int, Int> { return Pair(10, 20)}fun (): Triple<String, Int, String> { return Triple("Alice", 30, "Engineer")}fun () { // Destructuring Pair val (x, y) = getCoordinates() println("X: $x, Y: X: 10, Y: 20Name: Alice, Age: 30, Profession: Engineer
✅ 3. Destructuring in For Loops
You can destructure data within loops, especially when working with collections of pairs or maps.
📌 Example:
val userMap = mapOf("Alice" to 25, "Bob" to 30)for ((name, age) in userMap) { println("$name is data class Employee(val name: String, val age: Int, val position: String)val employee = Employee("John", 28, "Developer")val (name, _, position) = employeeprintln("Name: $name, Position: Name: John, Position: Developer
_
is used to ignore the age.
✅ 5. Custom Destructuring Using componentN()
You can define your own componentN()
functions for destructuring even if it's not a data class.
📌 Example:
class Point(val x: Int, val y: Int)// Custom component functionsoperator fun Point.() = xoperator fun Point.() = yfun () { val point = Point(5, 10) val (x, y) = point println("X: $x, Y: $y")}
Output:
X: 5, Y: 10
✅ Conclusion
Destructuring makes code clean and readable when dealing with complex data.
Best used with data classes, pairs, triples, or maps.
Use underscore (
_
) to ignore values.Implement
componentN()
for custom class support.