Deconstruction in Kotlin

There are times when you need to extract an object into a number of variables.

Let’s take the example below:

val (id, name, position, department) = employee

In Kotlin, this is known as a destructuring declaration. These new variables can now be used independently.

The compilation thereof would look something like this, but is not required:

val id = employee.component1()
val name = employee.component2()
val position = employee.component3()
val department = employee.component4()

Returning multiple values from a Function

Much like deconstruction of variables and collections, functions too can return multiple values.

// define a return object with multiple values
data class MultiValues(val someId: Int, val name: String)

// create our function to return multiple values
fun getDefaults(): MultiValues {
    val id = 123
    val name = "Andrew"
    return MultiValues(id, name)

// now get the values back
val (id, name) = getDefaults()

Destructuring on Maps

The same can be done for a map.

for ((key, value) in map) {
    // ...

When to use an _ (underscore) in Destructuring

Underscores (_) are used when you want to ignore the returned value in a specific position.

Let’s take the following example:

val (_, name) = getDefaults()

We will only have access to the name variable response now, and not the id.