Destructuring Declarations in Kotlin
Sometimes it’s easy to destructure an object into multiple variables of different properties instead of calling it again and again using . operator on the property or instance itself. It is beneficial for a few reasons like,
- We don’t have to use the dot property on the object again and again.
- 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.
- The defined variable will be alive within the defined scope.
- 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?
Let’s try to understand what is a destructuring declaration and how does it works internally.
Usually, when we declare a property, we can initialise it with some value or mark it nullable. If we want to extract a property from an object, we need to do that for each and every property, individually.
Kotlin provides functionality to do that in a single declaration where we can destructure the object into multiple variables within a single 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")
The output for the above print statement would be
Suneet at the age of 29 is working in Engineering department
How does it works internally?
The compiler internally uses the componentN function of Kotlin to destructure the object and assign them to the properties individually.
componentN is a functionality provided by Kotlin for any data class which return the Nth property (in sequence from the beginning) of that data class.
var (name, age, department) = employee// is equivalent tovar name = employee.component1()
var age = employee.component2()
var department = employee.component3()