TheJadav

Destructuring Declarations in Kotlin Android

What is Destructuring declaration?

It is term used in Kotlin programming language. Let’s assume we have a class named Data with field name, age, address. Sometimes we only need two of them in a particular code bloc so we can declare and initialize two variables at the same line. Yes you read it right, we can get value from Data class within single syntax. Let’s see it with example

data class Data(val name:String, val age:Int, val address:String)

 Initialize multiple variables from class member

val dataClass = Data("Lalit", 26, "Ahmedabad")
val (name, age, address) = dataClass

So, now we have three different variables. We can use name, age, address directly instead of dataClass.name. You might think why we need this kind of declaration, but before thinking about it see below example.

Return two variables from function

This situation is very interesting or may be you also have faced similar problem where you need multiple values to be return from single function. This post is solution for it.

fun function(...): Data { 
        // computations return Data(name, age, address) 
}

// Now, to use this function:
val (name, age) = function(...)

Got the difference? Our function is capable to return Data class but for now we just want to display user’s name and age so, we can just initialize these two variables.

Ignore unused variables

Here when we are using Destructuring declaration we need to make sure sequence of the variables are same as the constructer of the class. Do we need to define all the variables of the class?. Answer is yes and no. Thank to little symbol “_” (Underscore). Kotlin uses that symbol to ignore variable. If we want to get name and address we can modify function call like below.

val (name, _,address) = function(...)

In this case two variables created name and address. Remember that we can only use it in the sequence of the declaration in constructor. Means we can only use (name, age, address) sequence in our example, which we have declared in constructor. We can ignore trailing variables but can not middle and starting.

Conclusion

This is all about Destructuring declaration in kotlin, In Android you can use this in DiffUtil class where comparing arethedatasame method.

Share this content:

Share:

More Posts

How does data persistence work in Android?

Data persistence in Android is the ability to save data to the device so that it can be accessed later, even if the app is closed or the device is restarted. There are several ways to achieve data persistence in Android

Fragments and Activities: Two Pillars of Android Development

Fragments and Activities are both important components of Android development. Fragments are a good choice for creating reusable and dynamic UIs, while Activities are a good choice for managing the lifecycle of an app’s UI and implementing core features.

Table of Contents

Send Us A Message