Google News
logo
Kotlin - Interview Questions
What are destructuring declarations in Kotlin?
Destructuring declarations in Kotlin allow you to extract individual components from structured objects, such as data classes, arrays, or other types that provide component functions or extension functions with component-like signatures. It provides a concise way to assign multiple variables at once by extracting values from the object.

Here's how destructuring declarations work :

1. Destructuring Declarations with Data Classes :
   * When using destructuring declarations with data classes, the properties of the data class can be easily extracted into separate variables.
   * The number of variables on the left side of the assignment operator (`=`) must match the number of properties in the data class.
   Example :
     data class Person(val name: String, val age: Int)

     val person = Person("Alice", 25)
     val (name, age) = person
     println(name) // Alice
     println(age) // 25​

2. Destructuring Declarations with Arrays :
   * Destructuring declarations can also be used with arrays. In this case, each element of the array is assigned to a separate variable.
    Example :
     val numbers = arrayOf(1, 2, 3)
     val (a, b, c) = numbers
     println(a) // 1
     println(b) // 2
     println(c) // 3​
3. Destructuring Declarations with Custom Types :
   * Destructuring declarations can be used with custom types as long as the type provides component functions or extension functions with component-like signatures.
   * The component functions should return the individual components in the desired order.
    Example :
     class Point(val x: Int, val y: Int) {
         operator fun component1() = x
         operator fun component2() = y
     }

     val point = Point(3, 5)
     val (x, y) = point
     println(x) // 3
     println(y) // 5​

4. Ignoring Values :
   * If you're not interested in a particular value during destructuring, you can use an underscore (`_`) as the variable name to indicate that the value should be ignored.
   Example :
     val (_, age) = person
     println(age) // 25​
Destructuring declarations provide a convenient way to extract values from structured objects and assign them to individual variables in a concise and readable manner. It improves code readability and reduces boilerplate code when working with complex objects or collections.
Advertisement