Destructuring in Kotlin: Explained with Examples 📚✨

Mukesh RajputMukesh Rajput
4 min read

Destructuring in Kotlin is a feature that lets you easily unpack objects into multiple variables. This makes your code cleaner and easier to read. Here’s a simple guide to understanding and using destructuring in Kotlin.

What is Destructuring?

Destructuring allows you to break an object into its individual properties and assign them to separate variables in one line. For example, if you have a data class like this:

data class Student(val name: String, val age: Int)

You can use destructuring to get name and age directly:

val student = Student("Mukesh", 12)
val (name, age) = student
println("Name: $name, Age: $age")

Here, name and age are extracted from the student object.

//Output
Name: Mukesh, Age: 12

Using Destructuring with Data Classes

Data classes are ideal for destructuring. When you create a data class, Kotlin automatically provides functions to get each property.

For example:

data class LatLng(val lat: Double, val lng: Double)

fun main() {
    val latLng = LatLng(10.0, 20.0)
    val (lat, lng) = latLng
    println("x: $lat, y: $lng")
}

In this code, lat and lng are extracted from the latLng object.

//Output
x: 10.0, y: 20.0

Destructuring in Collections

Destructuring is also useful when working with collections. For example, if you have a list of pairs:

val coordinates = listOf(Pair(1, 2), Pair(3, 4), Pair(5, 6))

for ((x, y) in coordinates) {
    println("x: $x, y: $y")
}

Here, each Pair in the list is destructured into x and y.

//Output
x: 1, y: 2
x: 3, y: 4
x: 5, y: 6

Destructuring in Maps

When iterating over a map, you can destructure the entries into key-value pairs:

val map = mapOf("Mukesh" to 100, "Manish" to 200, "Amar" to 300)

for ((key, value) in map) {
    println("Key: $key, Value: $value")
}

This simplifies working with map entries.

//Output
Key: Mukesh, Value: 100
Key: Manish, Value: 200
Key: Amar, Value: 300

Custom Destructuring Declarations

You can also define how your own classes should be destructured by adding componentN functions. Here’s how you can do it:

//Always add operato keyword and component name with number
class StudentData(val name: String, val age: Int) {
    operator fun component1() = name
    operator fun component2() = age
}

fun main() {
    val studentData = StudentData("Mukesh", 10)
    val (name, age) = studentData
    println("Name: $name, Age: $age")
}

In this example, component1 and component2 functions allow destructuring the StudentData class.

//Output
Name: Mukesh, Age: 10

What happen if we change component function order?

In Kotlin, when using destructuring declarations, the order of the *componentN* functions in your class determines the order in which the properties are unpacked. Changing the order of these functions can lead to unexpected results. Let’s see what happens if you change the order of the *componentN* functions.

Consider the following StudentData class:

class StudentData(val name: String, val age: Int) {
    operator fun component2() = name
    operator fun component1() = age
}

Here, component2 returns the name, and component1 returns the age. In the main function, we destructure the studentData object:

fun main() {
    val studentData = StudentData("Mukesh", 10)
    val (name, age) = studentData
    println("Name: $name, Age: $age")
}

When you run this code, the output will be:

//Output
Name: 10, Age: Mukesh

Here’s why:

  • Destructuring Order: Kotlin expects component1() to correspond to the first property in the data class, and component2() to the second property. In the given StudentData class, component1() returns age, and component2() returns name.

  • Mismatch: As a result, name receives the age value, and age receives the name value, because Kotlin uses the component functions in the order they are defined.

Conclusion

Destructuring in Kotlin helps you handle objects and collections more easily by breaking them into separate variables. It’s a simple yet powerful feature that makes your code more readable and efficient. With this guide, you can start using destructuring in your Kotlin projects with confidence.

Feel free to experiment with these examples and see how destructuring can simplify your code! Happy coding! 🎉

0
Subscribe to my newsletter

Read articles from Mukesh Rajput directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Mukesh Rajput
Mukesh Rajput

Specializing in creating scalable and maintainable applications using MVVM and Clean Architecture principles. With expertise in Ktor, Retrofit, RxJava, View Binding, Data Binding, Hilt, Koin, Coroutines, Room, Realm, and Firebase, I am committed to delivering high-quality mobile solutions that provide seamless user experiences. I thrive on new challenges and am constantly seeking opportunities to innovate in the Android development space.