Kotlin Destructuring
Destructuring pulls the parts of one value into separate variables in a single declaration. The parts come out in the order the value stores them.
Destructuring a data class
The declaration takes the point apart into x and y. After that line the two parts are plain variables.
data class Point(val x: Int, val y: Int)
fun main() {
val point = Point(3, 4)
val (x, y) = point
println(x)
println(y)
println(x + y)
}Destructuring a Pair
A Pair holds exactly two values. Destructuring names both of them in one line.
fun main() {
val user = Pair("Ada", 36)
val (name, age) = user
println(name)
println(age + 1)
}Destructuring a list
A list gives its first items in order. Three names take the first three colors.
fun main() {
val colors = listOf("red", "green", "blue")
val (first, second, third) = colors
println(first)
println(second)
println(third)
}Skipping a part with an underscore
The middle part of the member is not needed here. An underscore holds its place and no variable is made for it.
data class Member(val name: String, val age: Int, val city: String)
fun main() {
val member = Member("Grace", 41, "Leeds")
val (name, _, city) = member
println(name)
println(city)
}Destructuring map entries in a loop
Each entry of a map is a key and a value together. The loop header destructures the entry, so the body uses plain names.
fun main() {
val scores = mapOf("Ada" to 91, "Grace" to 87)
for ((name, score) in scores) {
println("$name: $score")
}
}Example
data class Movie(val title: String, val year: Int, val rating: Double)
fun main() {
val movie = Movie("Arrival", 2016, 7.9)
val (title, year, rating) = movie
println(title)
println(year)
println(rating)
val credits = mapOf("director" to "Villeneuve", "star" to "Adams")
for ((role, person) in credits) {
println("$role = $person")
}
}Key points
- Write the new names in parentheses after val to destructure a value.
- A data class gives its parts in the order its constructor lists them.
- A Pair destructures into its first and second values.
- A list destructures into its first few items, one name per item.
- Write an underscore for a part that the program does not need, and that part is skipped.
- Destructure map entries in a loop header to get each key and value as named variables.
In this example a movie value is taken apart into its title, year and rating in one declaration. A credits map is then looped with destructured entries, so each role and person prints under its own name.
Note
The names in a destructuring declaration are new variables, so they can be any names the program chooses.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Kotlin Playground
Exercise
A data class Point holds x and y in that order. A program writes val (x, y) = Point(2, 5) and then prints x + y. What does it print?