Destructuring Declarations in Kotlin
Introduction
Destructuring Declarations is a fundamental concept every Kotlin developer should understand. Type aliases and destructuring declarations make Kotlin code more readable and expressive without changing runtime behaviour.
Destructuring unpacks an object into multiple variables in one statement. In this tutorial you will learn the syntax, walk through a complete example program, study the sample output, and review best practices so you can apply the concept confidently in your own projects.
Definition
- Destructuring unpacks an object into multiple variables in one statement.
- Data classes automatically generate componentN functions for destructuring.
- Destructuring works in for loops, val declarations, and lambda parameters.
Syntax
val (name, age) = person
for ((key, value) in map) { }Destructuring Declarations in Kotlin Example Program in Kotlin
data class Person(val name: String, val age: Int)
fun main() {
val person = Person("Anita", 28)
val (name, age) = person
println("Name: $name, Age: $age")
val pairs = listOf("a" to 1, "b" to 2)
for ((letter, number) in pairs) {
println("$letter -> $number")
}
}Sample Output
Name: Anita, Age: 28
a -> 1
b -> 2When to use
Use type aliases for long generic types; use destructuring when unpacking data classes or pairs in loops.
How it works
-
The program starts with a
mainfunction — the entry point that runs when you execute the file. -
Destructuring unpacks an object into multiple variables in one statement.
-
Run the program in IntelliJ IDEA, Android Studio, or with the Kotlin command-line compiler (
kotlinc/kotlin). Compare your console output with the sample output shown below.
Best Practices
Common Mistakes
Key Points
- Destructuring unpacks an object into multiple variables in one statement.
- Data classes automatically generate componentN functions for destructuring.
- Destructuring works in for loops, val declarations, and lambda parameters.
- Test the example locally and verify the output matches the sample.
- Experiment by changing input values to see how behaviour changes.
Notes
- Semicolons at the end of statements are optional in Kotlin.