Kotlin Tips & Tricks(2): Destructuring Declarations in Kotlin

you can see part 1

deconstruct an object into a series of variables. A destructive declaration will create multiple variables at the same time.

data class Person(val title: String, val age: Int)
val person = Person(title, age)
val (title, age) = person

A destructive declaration is compiled into the following code:

val name = person.component1()
val age = person.component2()

Anything can be placed to the right of the destructor declaration as long as the required number of component functions can be called. Of course, there can becomponent3()withcomponent4()and many more.

Destructuring statements can also be used in loops

Tricks(1) Destructuring (for lambda parameters)

you should use parentheses that include all the parameters that we want to destructure into

val showUser: (Person) -> String = { (title, age) -> 
return "name is $title and age is = $age "
}

A destructive declaration is compiled into the next code:

val name = person.component1()
val age = person.component2()

In lambda expressions, and statements declare two parameters a combination of deconstruction is not the same

{ a, b -> … } // two parameters
{ (a, b) -> … } // a destructured pair

Tricks(2) Kotlin destructuring more than five components

  • if you try to use more than 5 pararmeter will get this
    must have a 'component6()' function

Note that the componentN() functions need to be marked with the operator keyword to allow using them in a destructuring declaration.

first of all we make person class

data class Person(val a:Int,val b:Int,val c:Int,val d:Int,val e:Int,val f:Int)
operator fun Person.component6() = this.f
  • here I made new operator to add component6() and make initial value
operator fun Person.component6() = this.f
  • now we can use destruct here
val (a,b,c,d,e,f) = Person(1,2,3,4,5,6)
println(“a is $f”)

Trick(3) A function returns two values with destruction

  • we can user Pair<Status,String>
fun insert(name: String?, age: Int?): Pair<Status,String> {}
  • using destruction help
data class Result(val status: Status, val message:String)fun insert(…): Result {
// computations
return Result(status,message)
}
// Now, to use this function:
val (status,message) = insert(…)

If deconstruction of a variable declaration, if you do not use, you can use an underscore instead of its name, such as:

val (_, status) = insert()

Mobile Developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store