Kotlin Destructuring Data Class Objects Tutorial

In this section, we will learn how to destruct a data class object in Kotlin.

Note: we’re assuming you’re already familiar with the Kotlin data class type.

What is Destructuring a Data Class Object in Kotlin?

Destructuring a data class object is the process of extracting its values and assign that to multiple variables in one statement.

How to destructure a data class object in Kotlin?

This is the syntax of destructuring a data class object:

var (var_1, var_2, var_n) = object

On the left side of the assignment operator, create the same number of variables as the number of properties available for the target object.

So now, the value of the first property of the object will be assigned to the var_1, the second property’s value will be assigned to the var_2 and so on until all the properties’ values are assigned to the related variables.

Note that the number of variables we create can be less than the number of properties of the target object! For example, let’s say the number of properties of an object is 4 but we have 2 variables only. In a situation like this, the first two properties’ values of the target object will be assigned to the variables and the rest of properties of the target object will be skipped.

Example: destructuring a data class object in Kotlin

data class Person(val firstName:String, val lastName:String){
    var age  = 10
}

fun main(){
    
    var person = Person("John","Doe")
 
    var (fName,lName) = person 

    println("The first name is: $fName and the last name is: $lName")
}

Output:

The first name is: John and the last name is: Doe

How does data class object destructing work in Kotlin?

As you can see, the person object is of type Person data class and so, it can be used in the destructuring process.

So here we have created two variables named fName and lName respectively and so the value of the firstName property will be assigned to the fName and the value of the lastName property will be assigned to the lName variable.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies