Table of contents
1.
Introduction
2.
Destructuring Declarations
3.
Using underscores for unused variables
4.
Using Lambda Parameters with Destructuring Declaration
5.
FAQs
6.
Key Takeaways  
Last Updated: Mar 27, 2024

Kotlin - Destructuring Declarations

Author Pradeep Kumar
1 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In this blog, we will discuss Destructuring Declarations in KotlinDestructuring 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

Using underscores for unused variables

In a destructuring declaration, we can use an underscore in place of a non-required variable. If you don’t need the value of one or more variables, an underscore can be used in the place of that variable. For example,

// Creating rectangleData using the data class
data class rectangleData(val length:Int,val width:Int)

// 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 (_,width) = rectangle
    // printing the value of width
    println("Width of the rectangle: "+ width)
}

Output:

Width of the rectangle: 50

In the above example, we used an underscore in place of the length variable. Here, we only needed the width of the rectangle, so we used an underscore to ignore the value of the length variable.

Using Lambda Parameters with Destructuring Declaration

We can use the lambda functions with destructuring declarations to make some in place changes. Lamba is a function without a name, and it is defined using curly braces {}. Inside the curly braces, we first pass the value of variables, followed by an arrow(->) operator. After the arrow operator, we write the body of the function. 

Syntax of Lambda

{variables -> function_body}

In the example below, we will see how we can change the value of a map using destructuring declarations with a lambda function:

fun main(){
    // Initialising a map from int to int
    val squares = mutableMapOf<Int,Int>()
    squares.put(1,1)
    squares.put(2,4)
    squares.put(3,9)
    squares.put(4,16)
    squares.put(5,25)
    print("Old map is: ")
    println(squares)
    // Changing the key value
    val cubes = squares.mapValues { (key,value) -> value*key }
    print("New Map: ")
    println(cubes)
}

Output:

Old map is: {1=1, 2=4, 3=9, 4=16, 5=25}
New Map: {1=1, 2=8, 3=27, 4=64, 5=125}

In this example, we have used both key and value. In case you don’t need one or both of these, you can use an underscore in place of them. For example,

fun main(){
    // Initialising a map from int to int
    val squares = mutableMapOf<Int,Int>()
    squares.put(1,1)
    squares.put(2,4)
    squares.put(3,9)
    squares.put(4,16)
    squares.put(5,25)
    print("Old map is: ")
    println(squares)
    // Using _ in place of key
    val square_2 = squares.mapValues { (_,value) -> value*value }
    print("New Map: ")
    println(square_2)

    // Using _ in place of both keys and values
    val unit_map = square_2.mapValues { (_,_) -> 1 }
    print("Unit Map: ")
    println(unit_map)
}

Output:

Old map is: {1=1, 2=4, 3=9, 4=16, 5=25}
New Map: {1=1, 2=16, 3=81, 4=256, 5=625}
Unit Map: {1=1, 2=1, 3=1, 4=1, 5=1}

As we can see from the above example, an underscore can be used in place of either key or value or both. 

FAQs

  1. How is a data class different from a class in Kotlin?
    Data class is a class that only contains a state. It doesn’t perform any operation. It only holds the data.
     
  2. How are lambda expressions different from normal functions?
    A lambda expression is just a function without a name. It is written at the place it needs to be used.
     
  3. Can we use an underscore at more than one place in a destructuring declaration?
    Yes, an underscore can be used at any number of places in a destructuring declaration. It will simply ignore the value of all the fields marked as underscores.

Key Takeaways  

Cheers if you reached here!!!

In this blog, we discussed Destructuring Declarations in Kotlin. Additionally, we looked at lambda expressions. We saw how lambdas and underscores could be used with Destructuring Declarations.

After reading this blog, I believe you will work with Destructuring Declarations smoothly. If you wish to learn about Kotlin functions in detail, you can check out our other blog on Kotlin FunctionsAnd to learn in-depth about android development, check out our Android Development course on the Coding Ninjas website.

Live masterclass