Learn Kotlin- Destructuring Declarations

Learn Kotlin Destructuring declarations

Destructuring Declarations

Destructuring Declarations is yet another important feature available in Kotlin. We can take advantage of this feature to write a better application.

What is Destructuring?

Destructuring is a convenient way of extracting multiple values from data stored in (possibly nested) objects and Arrays. It can be used in locations that receive data (such as the left-hand side of an assignment).

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

val (name, age) = developer

Now, we can use name and age independently like below:

println(name)
println(age)

Use-cases where we can use the Destructuring feature:

  • Returning Two Values from a Function

Example

data class Developer(val name: String, val age: Int)
fun getDeveloper(): Developer {
 // some logic
 return Developer(name, age)
}

// Now, to use this function:
val (name, age) = getDeveloper()
  • Destructuring Declarations and Maps

Example

for ((key, value) in map) {
 // do something with the key and the value
}

So use this Destructuring feature, when it is required.