Destructuring Declarations in Kotlin

Kotlin provides the programmer with a unique way to work with instances of a class, in the form of destructuring declarations. A destructuring declaration is the one that creates and initializes multiple variables at once.
For example :

val (emp_id,salary) = employee

These multiple variables correspond to the properties of a class that are associated with an instance. These variables can be used independently in any way you want.

println(emp_id+" "+salary)

The destructing declaration works on the concept of component() functions. The number of variables that a destructing declaration can define, the class provide those number of component functions, starting from component1(), component2() up to componentN(). The data class in Kotlin by default implement component functions.

Destructuring declaration compiled to following code:-

val emp_id = employee.component1()
val salary = employee.component2()

Kotlin program of returning two values from a function –

filter_none

edit
close

play_arrow

link
brightness_4
code

// A sample data class
data class Data(val name:String,val age:Int)
   
// A function returning two values
fun sendData():Data{
    return Data("Jack",30)
}
   
fun main(){
    val obj = sendData()
    //  Using instance to access properties
    println("Name is ${obj.name}")
    println("Age is ${obj.age}")
   
    // Creating two variables using  destructing declaration
    val (name,age) = sendData()
    println("Name is $name")
    println("Age is $age")
   
}

chevron_right


Output:

Name is Jack
Age is 30
Name is Jack
Age is 30

Note: The component function definitions must be preceded by the operator keyword if to be used in a destructuring declaration.

Underscore for unused variables
Sometimes, you might want to ignore a variable in a destructuring declaration. To do so, put an underscore in place of its name. In this case, the component function for the given variable isn’t invoked.

Destructuring declaration in lambdas –

Following the arrival of Kotlin 1.1, the destructing declaration syntax can be used for lambda parameters also. If a lambda parameter has a parameter of Pair type or some other type that declares component functions, then we can introduce new parameters by putting them in parenthesis. The rules are the same as defined above.

Kotlin program of using destructuring declaration for lambda parameters –

filter_none

edit
close

play_arrow

link
brightness_4
code

fun main(){
    val map = mutableMapOf<Int,String>()
    map.put(1,"Ishita")
    map.put(2,"Kamal")
    map.put(3,"Kanika")
    map.put(4,"Minal")
    map.put(5,"Neha")
    map.put(6,"Pratyush")
    map.put(7,"Shagun")
    map.put(8,"Shashank")
    map.put(9,"Uday")
    map.put(10,"Vandit")
    println("Initial map is")
    println(map)
    // Destructuring a map entry into key and values
    val newmap = map.mapValues { (key,value) -> "Hello ${value}" }
    println("Map after appending Hello")
    println(newmap)
}

chevron_right


Output:

Initial map is
{1=Ishita, 2=Kamal, 3=Kanika, 4=Minal, 5=Neha, 6=Pratyush, 7=Shagun, 8=Shashank, 9=Uday, 10=Vandit}
Map after appending Hello
{1=Hello Ishita, 2=Hello Kamal, 3=Hello Kanika, 4=Hello Minal, 5=Hello Neha, 6=Hello Pratyush, 7=Hello Shagun, 8=Hello Shashank, 9=Hello Uday, 10=Hello Vandit}

If a component of the destructured parameter is not in use, we can replace it with the underscore to avoid calling component function:

map.mapValues { (_,value) -> "${value}" }


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.