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:
age, and can use them independently:
A destructuring declaration is compiled down to the following code:
component2() functions are another example of the principle of conventions widely used in Kotlin (see operators like
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
component4() and so on.
Destructuring declarations also work in
b get the values returned by
component2() called on elements of the collection.
Example: returning two values from a function
Assume that you need to return two things from a function - for example, a result object and a status of some sort. A compact way of doing this in Kotlin is to declare a data class and return its instance:
Since data classes automatically declare
componentN() functions, destructuring declarations work here.
Example: destructuring declarations and maps
Probably the nicest way to traverse a map is this:
To make this work, you should
Present the map as a sequence of values by providing an
Present each of the elements as a pair by providing functions
And indeed, the standard library provides such extensions:
So you can freely use destructuring declarations in
for -loops with maps (as well as collections of data class instances or similar).
Underscore for unused variables
If you don't need a variable in the destructuring declaration, you can place an underscore instead of its name:
componentN() operator functions are not called for the components that are skipped in this way.
Destructuring in lambdas
You can use the destructuring declarations syntax for lambda parameters. If a lambda has a parameter of the
Pair type (or
Map.Entry, or any other type that has the appropriate
componentN functions), you can introduce several new parameters instead of one by putting them in parentheses:
Note the difference between declaring two parameters and declaring a destructuring pair instead of a parameter:
If a component of the destructured parameter is unused, you can replace it with the underscore to avoid inventing its name:
You can specify the type for the whole destructured parameter or for a specific component separately: