Search⌘ K
AI Features

Destructing

Explore the concept of position-based destructuring in Kotlin, which allows assigning multiple variables from an object's components. Understand how data classes generate component functions, the pros and cons of this feature, and best practices to avoid errors when destructuring. Gain insights into using destructuring in lambdas for concise code access to properties.

Exploring position-based destructuring

Kotlin supports a feature called position-based destructuring, which lets us assign multiple variables to components of a single object. For that, we place our variable names in parentheses.

Kotlin 1.5
data class Player(
val id: Int,
val name: String,
val points: Int
)
fun main() {
val player = Player(0, "Gecko", 9999)
val (id, name, pts) = player
println(id) // 0
println(name) // Gecko
println(pts) // 9999
}

Destructuring mechanism

This mechanism relies on position, not names. The object on the right side of the equality sign needs to provide the functions component1, component2, etc., and the variables are assigned to the results of these methods.

val (id, name, pts) = player
// is compiled to
val id: Int = player.component1()
val name: String = player.component2()
val pts: Int = player.component3()
The mechanism behind position-based destructuring

This code works ...