Introduction
In this blog, we will discuss Destructuring Declarations in Kotlin. Destructuring Declarations are used to declare multiple variables at once. We will also look at lambda expressions and will see how they can be used with Destructuring Declarations. If you are not familiar with lambda expressions, you can check out our article on Kotlin Lambda Expressions first.
Sometimes, not all the variables are needed in a Destructuring Declaration; in that case, we can use an underscore in place of those variables. We will discuss underscores in detail and see how an underscore can be used in a Destructuring Declaration.
Destructuring Declarations
Destructuring Declarations is a unique way of working with instances of a class. It can be used to initialize multiple variables at a time. In the code snippet given below, we can see how multiple variables can be declared at once:
val (length, width) = rectangle
All the variables initialized using destructing declarations can be used independently in any manner.
println("Length of the rectangle:", length)
println("Width of the rectangle:", width)
A program to demonstrate the working of destructing declarations:
// Creating rectangleData using the data class
data class rectangleData(val length:Int, val width:Int)
// This function returns two values
fun rectangle():rectangleData{
return rectangleData(100,50)
}
fun main(){
// Creating two variables using destructing declaration
val (length, width) = rectangle()
// printing the variables
println("Length of the rectangle: " + length)
println("Width of the rectangle: " + width)
}
Output:
Length of the rectangle: 100
Width of the rectangle: 50
Here we have used the data class of Kotlin to create an object with two values. In Kotlin, the Data class is used to hold data. It contains a lot of built-in functionality to make working with data easier.
Another way to fetch different values from a class is to use the component() function. The number of component functions provided by a class is the same as the number of variables that a destructuring declaration. To fetch the first value of the class, the component1() function can be used. Similarly, the componentN() function can be used to fetch the nth value. In the below example, we use component1() and component2() to fetch the value of length and width, respectively:
// This function returns two values
fun createRectangle():rectangleData{
return rectangleData(100,50)
}
fun main(){
// Calling createRectangle() function to get the parameters of rectangle
var rectangle = createRectangle()
// Using the component function to get the values of length and width
val length= rectangle.component1()
val width= rectangle.component2()
// printing the variables
println("Length of the rectangle: "+ length)
println("Width of the rectangle: "+ width)
}
Output:
Length of the rectangle: 100
Width of the rectangle: 50




