Destructuring declarations

Edit pageLast modified: 25 September 2024

Sometimes it is convenient to destructure an object into a number of variables, for example:

This syntax is called a destructuring declaration. A destructuring declaration creates multiple variables at once. You have declared two new variables: name and age, and can use them independently:

A destructuring declaration is compiled down to the following code:

The component1() and component2() functions are another example of the principle of conventions widely used in Kotlin (see operators like + and *, for-loops as an example). Anything can be on the right-hand side of a destructuring declaration, as long as the required number of component functions can be called on it. And, of course, there can be component3() and component4() and so on.

Destructuring declarations also work in for-loops:

Variables a and b get the values returned by component1() and component2() called on elements of the collection.