Destructuring Declarations
Destructuring Declarations
Sometimes it is convenient to destructure an object into a number of variables, for example:
val (name, age) = person
This syntax is called a destructuring declaration. A destructuring declaration creates multiple variables at once. We have declared two new variables: name
and age
, and can use them independently:
println(name) println(age)
A destructuring declaration is compiled down to the following code:
val name = person.component1() val age = person.component2()
The component1()
and component2()
functions are another example of the principle of conventions widely used in Kotlin (see operators like +
and *
, for-loops etc.). Anything can be on the right-hand sid