CodeGym /Courses /Kotlin SELF /Destructuring a data class: componentN() and readabilit...

Destructuring a data class: componentN() and readability criteria

Kotlin SELF
Level 33, Lesson 3
Available

1. Remembering destructuring

If you’ve ever looked at an object and thought, “I just need to quickly pull two fields out of it — and that’s it,” then you’re already emotionally ready for destructuring.

Destructuring — is Kotlin syntax that lets you “take apart” an object into several variables in a single line. But this convenience comes with a cost: readability depends on names and context, and the field order suddenly becomes important.

Let’s start with a simple example based on our console “expense tracker” (we’ve been evolving it since the moment we moved from Pair to proper models).

data class Expense(val title: String, val category: String, val amountRub: Int)

fun main() {
    val e = Expense("Coffee", "Food", 250)

    val (title, category, amount) = e
    println("Purchase: $title, category: $category, amount: $amount ₣ ")
    // Purchase: Coffee, category: Food, amount: 250 ₣
}

Here val (title, category, amount) = e looks almost like “magic.” But in Kotlin, magic is usually billed at the strict “there are honest functions under the hood” rate. And now we’ll see them.

2. componentN(): what a data class generates

For destructuring to work, Kotlin looks for special functions on the object: component1(), component2(), component3(), and so on.

For a data class, the compiler generates these functions automatically — exactly for the primary-constructor properties and strictly in the order they are declared. This is part of the standard “auto-generation” bundle for data class along with equals()/hashCode()/toString()/copy().

So for Expense(title, category, amountRub) the logic is roughly: component1() returns title, component2() returns category, component3() returns amountRub.

Let’s look at it “head-on” via direct calls:

data class Expense(val title: String, val category: String, val amountRub: Int)

fun main() {
    val e = Expense("Fare", "Transport", 60)

    println(e.component1()) // Fare
    println(e.component2()) // Transport
    println(e.component3()) // 60
}

What destructuring expands to

When you write a destructuring declaration, Kotlin effectively turns it into a series of componentN() calls. This matters not for pedantry, but so you won’t be surprised by why field order affects the result so much, and why destructuring is not “access by name” but “access by position.”

Schematically, it looks like this:

flowchart TD
    A["val (a, b, c) = obj"] --> B["val a = obj.component1()"]
    B --> C["val b = obj.component2()"]
    C --> D["val c = obj.component3()"]

That’s exactly why changing the order of properties in a data class is not just “cosmetics,” but a potential change in meaning across all code that used destructuring.

To make this connection explicit, it can be handy to keep a mini-table around (especially when the class is small but used heavily):

Position in the primary constructor Method What it returns for Expense(title, category, amountRub)
1
component1()
title
2
component2()
category
3
component3()
amountRub

And once again: this is the direct generation rule for a data class.

3. Practice: where destructuring is convenient

In tutorial examples, destructuring often looks like a “look what you can do” trick. In real code it’s useful in places where you already treat an object as a set of fields: printing, simple aggregation, preparing strings, iterating a collection “and immediately outputting.”

Formatting and output

Suppose we have a list of expenses and we want to print them as a table. You can write e.title, e.category, e.amountRub — and that’s fine. But sometimes destructuring makes the code shorter without losing meaning.

data class Expense(val title: String, val category: String, val amountRub: Int)

fun printExpense(e: Expense) {
    val (title, category, amount) = e
    println("$title | $category | $amount ₣ ")
}

fun main() {
    val items = listOf(
        Expense("Coffee", "Food", 250),
        Expense("Metro", "Transport", 60)
    )

    for (e in items) {
        printExpense(e)
    }
    // Coffee | Food | 250 ₣
    // Metro | Transport | 60 ₣
}

Why does it look appropriate here? Because we immediately gave the variables meaningful names, and the function is doing formatting — i.e., “pull out fields and assemble a string” is its entire job.

_ in destructuring: how to skip what you don’t need

Sometimes you need to extract only one or two values and ignore the rest. Kotlin lets you “skip” a component using _. This is not just saving characters, but also a way to make intent obvious: “this part exists, but I’m consciously not using it.”

Let’s imagine that for a report we only need the amount, and the title and category don’t matter (don’t ask why — accounting sometimes lives by the laws of a parallel universe).

data class Expense(val title: String, val category: String, val amountRub: Int)

fun main() {
    val e = Expense("Subscription", "Services", 499)

    val (_, _, amount) = e
    println("Amount: $amount ₣ ") // Amount: 499 ₣
}

Here _ works like “a variable that won’t exist.” Importantly, Kotlin does not create hidden variables for you with names like unused1: you are explicitly telling the language “don’t declare anything for this position.”

At the same time, _ works well when the omission is obvious. If you see val (_, _, amount) = e and you don’t immediately wonder “what was in the first two slots?”, then the context is appropriate. If you do wonder — it may be better to write e.amountRub and not torture the reader.

Destructuring in parameters: lambdas and withIndex()

Destructuring can appear not only in val (a, b) = ..., but also directly in parameters — for example, in lambdas. This often comes up when working with collections: you iterate over pairs like “index + value” or “key + value,” and you want to get both immediately.

A classic example is withIndex(). It provides pairs (conceptually) “index + element,” and Kotlin lets you write a loop with destructuring.

fun main() {
    val names = listOf("Ann", "Bob", "Cara")

    for ((index, name) in names.withIndex()) {
        println("$index -> $name")
    }
    // 0 -> Ann
    // 1 -> Bob
    // 2 -> Cara
}

In strict specification terms, parameter destructuring is part of the multi-declarations mechanism: the parameter is considered one, but inside you can split it into components if componentN() is available.

Important: in a regular function’s parameters, you must specify the type even if you destructure it into parts.

A small example with an actual function (not a lambda) to feel the difference:

data class Expense(val title: String, val category: String, val amountRub: Int)

fun printShort((title, _, amount): Expense) {
    println("$title: $amount ₣ ")
}

fun main() {
    printShort(Expense("Coffee", "Food", 250)) // Coffee: 250 ₣
}

It looks impressive, but now the readability question kicks in. For learning purposes — useful. For a real project — use with caution: sometimes it’s simpler and clearer to write fun printShort(e: Expense) and access e.title, e.amountRub.

4. Readability and pitfalls

Destructuring is like hot sauce. A little — tasty; a lot — you’re crying, and it no longer matters why. The main criterion is how easy it is for the reader to understand what exactly is stored in each variable without opening the data class declaration.

When destructuring improves the code

Good destructuring usually looks like this: variables are named by meaning, several components are used right away, and the object in that spot is indeed perceived as a “set of values.”

data class Expense(val title: String, val category: String, val amountRub: Int)

fun main() {
    val (title, category, amountRub) = Expense("Metro", "Transport", 60)
    println("$title / $category / $amountRub ₣ ")
    // Metro / Transport / 60 ₣
}

Bad destructuring often looks like this: val (a, b, c) = expense. Technically it works, but the meaning disappears. In a 6-line practice task — still tolerable. In code you’ll maintain a month later — it becomes “variable archaeology.”

Another important criterion is “how many fields.” Destructuring 2 values is usually fine (think Pair, withIndex(), Map.Entry). Destructuring 5–7 values is almost always a sign the reader will suffer, and it’s better to access properties by name.

And lastly: if you need only one field, destructuring almost never beats expense.amountRub. It’s shorter only in the number of dots, but longer in cognitive load: the reader has to remember the field order.

Field order and refactoring: “silent” meaning bugs

In Kotlin, componentN() is rigidly tied to the order of properties in the primary constructor of a data class. That means a simple “I’ll reorder the fields to look nicer” can change the meaning of destructuring across the whole project.

Imagine it used to be:

data class Expense(val title: String, val category: String, val amountRub: Int)

And then you decided it’s more logical to keep the amount before the category:

data class Expense(val title: String, val amountRub: Int, val category: String)

If somewhere in the code you had:

val (title, category, amount) = expense

then now category will suddenly become a number and amount will become a string… and the compiler will most likely catch it via types.

But it can be worse: if the types match (for example, two String in a row — title and category), then the compiler won’t notice, and the meaning changes silently.

That’s one reason to use destructuring where you’re confident: the order is stable, the model is small, and the context is obvious. If the model is “alive” and changes often, accessing properties by name is usually safer.

5. Typical mistakes when destructuring a data class

Mistake #1: destructuring for a single variable.
A very common scenario: “I only need amountRub, but I’ll write val (_, _, amount) = e.” Technically it’s correct, but the reader has to recall the field order, and you have to preserve that order as the model changes. In this situation it’s almost always simpler and clearer to write val amount = e.amountRub.

Mistake #2: variables a, b, c and losing meaning.
Beginners sometimes enjoy writing shorter code and end up with val (a, b, c) = expense. That quickly turns the code into a riddle: a week later you no longer remember what b is, and the IDE does not always save you, because “go to declaration” takes you to a place where you see b again. Destructuring works well only when names reflect the meaning of the data.

Mistake #3: blind faith that “the order is obvious.”
The field order in a data class seems obvious right up until the first refactor, when someone “just a little bit” rearranges constructor parameters. Since componentN() depends on order, not names, destructuring can start to mean something else. This is especially dangerous if multiple fields have the same type (for example, two String fields). In such models, it’s safer to access properties by name.

Mistake #4: destructuring in function parameters where simplicity is needed.
The syntax fun f((a, b): Pair<Int, Int>) or fun printShort((title, _, amount): Expense) looks impressive and even a bit “hacky.” But if the team (or you) isn’t used to this style yet, readability suffers: it’s harder to see “what is the parameter type of this function.” It’s better to keep this trick for short lambdas and very local spots, and for public functions more often choose a regular parameter expense: Expense.

Mistake #5: expecting destructuring to work “for any class.”
Destructuring is possible only if componentN() functions exist. For a data class, they are generated automatically based on primary-constructor properties, but a regular class may not have them. So if you removed data or moved the needed fields out of the primary constructor, destructuring may suddenly stop compiling — and that is normal, expected behavior.

1
Task
Kotlin SELF, level 33, lesson 3
Locked
Book card
Book card
1
Task
Kotlin SELF, level 33, lesson 3
Locked
Coordinate sensor
Coordinate sensor
1
Task
Kotlin SELF, level 33, lesson 3
Locked
Badge without email
Badge without email
1
Task
Kotlin SELF, level 33, lesson 3
Locked
To-do list
To-do list
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION