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
Code language: Kotlin (kotlin)

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()
Code language: Kotlin (kotlin)

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()
Code language: Kotlin (kotlin)

Destructuring on Maps

The same can be done for a map.

for ((key, value) in map) { // ... }
Code language: Kotlin (kotlin)

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()
Code language: Kotlin (kotlin)

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

Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments