Skip to Content
Course content

42: Destructuring Declarations

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Imagine you've just ordered a "Value Meal" from a drive-thru. The employee hands you one single brown paper bag. Inside that one bag, you know there's a burger, a side of fries, and a drink. You don't want to keep the bag closed and reach inside every time you want a sip of your drink or a fry; instead, the first thing you do when you get to your table is reach in and set the burger, the fries, and the drink out in front of you as three distinct items.

Destructuring declarations in Kotlin are exactly like that. You have one object (the bag), but you want to "unpack" its properties into separate, individual variables (the burger, fries, and drink) in a single line of code, rather than accessing them one by one via dot notation.

Tearing Open the Bag

You'll see this most often with data classes. Because data classes are designed to hold data, Kotlin automatically generates the machinery needed to let you pull the values out. Let's say we're building a system to track employees in a company.

data class Employee(val name: String, val role: String, val id: Int)

fun main() {
    val emp = Employee("Sarah", "Lead Engineer", 1024)

    // Instead of doing this:
    // val name = emp.name
    // val role = emp.role
    // val id = emp.id

    // Do this:
    val (employeeName, employeeRole, employeeId) = emp

    println("Employee $employeeName is the $employeeRole (ID: $employeeId)")
}

Notice that I didn't have to name the variables name, role, and id. I can name them whatever I want. The order is what matters. Kotlin looks at the order of the properties defined in the Employee class and assigns them to the variables in the parentheses in that exact same order.

Where the Magic Actually Happens

I want you to understand what's happening under the hood, because it'll help you when you run into weird bugs. Kotlin isn't actually doing some mystical "splitting" of the object. When you define a data class, Kotlin automatically creates functions called component1(), component2(), and so on.

When you write val (a, b) = object, Kotlin is actually translating that to:

  • val a = object.component1()
  • val b = object.component2()

This is why destructuring works out of the box for Pair and Triple classes too. They are essentially just data classes with component functions. If you ever create a regular class (not a data class) and you want it to be destructurable, you can actually write your own operator fun component1() functions manually. I'll be honest: you rarely need to do this, but it's a neat trick to have in your back pocket.

Throwing Away the Extras

Sometimes, you get a "Combo Meal" but you're not feeling the fries. In programming, we often destructure an object but realize we only need one or two of the values. If you define variables for things you don't intend to use, the IDE will probably give you a warning, and it just clutters up your code.

Kotlin handles this with an underscore (_). It tells the compiler, "I know there's a value here, but I don't care about it; just skip it."

val (name, _, id) = emp 
// We grabbed the name and the id, but we ignored the role.

This keeps your scope clean. I use this constantly when working with Pair objects returned from map iterations or helper functions where the second value is just a status code I don't need to log.




📋 Practical Task

Parsing a Weather Station Reading

You are writing a module for a weather app. You have a data class called WeatherReading that contains the city, temperature, humidity, and windSpeed.

Your task is to write a function called printWeatherSummary that takes a WeatherReading object as an argument. Inside the function, use a destructuring declaration to extract the city and the temperature, while ignoring the humidity and windSpeed. Finally, print a string in the format: "The current temperature in [city] is [temperature] degrees."

data class WeatherReading(
    val city: String, 
    val temperature: Double, 
    val humidity: Int, 
    val windSpeed: Double
)

fun printWeatherSummary(reading: WeatherReading) {
    // Your code here
}

fun main() {
    val today = WeatherReading("Seattle", 14.5, 82, 12.0)
    printWeatherSummary(today)
}
Rating
0 0

There are no comments for now.

to be the first to leave a comment.