Destructuring Declarations in Kotlin

  1. We don’t have to use the dot property on the object again and again.
  2. If the object is of a nullable type, we can do the null check only once and then we can destructure it to non-nullable properties.
  3. The defined variable will be alive within the defined scope.
  4. Fewer chances of confusion and more readability.
This post was originally posted at https://agrawalsuneet.github.io/blogs/destructuring-declarations-in-kotlin/ and reposted on Medium on 03rd Dec 2021.

What is destructuring declaration?

data class Employee (val name : String,
val age: Int,
val department: String)
var employee = Employee(name = "Suneet", age = 29, department = "Engineering")

var (name, age, department) = employee

println("$name at the age of $age is working in $department department")
Suneet at the age of 29 is working in Engineering department

How does it works internally?

var (name, age, department) = employee// is equivalent tovar name = employee.component1()
var age = employee.component2()
var department = employee.component3()

Please continue reading at https://agrawalsuneet.github.io/blogs/destructuring-declarations-in-kotlin/

--

--

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