CodeGym /Courses /Kotlin SELF /Destructuring: val (a, b) and _

Destructuring: val (a, b) and _

Kotlin SELF
Level 10, Lesson 2
Available

1. Destructuring Pair and Triple

If you’re just starting to program, reading via first/second seems fine: “well, there are fields — so I just take them.” But pretty quickly the code turns into a small quest: where first is x, and where first is min, and where first is an “error message”? Destructuring solves this in a simple way: you immediately give the components reasonable names, and then the code reads like plain text.

The second reason is local readability. When you “unfold” a Pair into x and y, you no longer have to keep in your head what first meant. Variables become self-documenting. And this is that rare case where the compiler not only complains, but also helps you write clearer code.

Pair: val (a, b) = pair

The most common option is to unpack a Pair into two variables. The syntax looks like we are “assigning to two variables at once,” although technically it’s still one expression on the right and one declaration on the left.

Let’s start with the simplest possible example:


fun main() {
    val point = 10 to 20

    val (x, y) = point
    println("x=$x y=$y") // x=10 y=20
}

Notice two things. First, on the left we declared two variables x and y. Second, the meaning of first/second is now “baked into” the names: x is the first, y is the second, and the reader of the code is not obligated to remember that somewhere there is a Pair.

Destructuring vs. first/second: when which is more convenient

Sometimes the logic is: you use both parts — then destructuring usually wins. If you only need one part, sometimes it’s simpler to take pair.first or pair.second. To avoid arguing, you can think of it like this: destructuring is good when you will then use the components separately many times, and first/second is good when you take one component once and apply it immediately.

Let’s compare with an example:

fun main() {
    val range = 1 to 100

    // Option A: without destructuring
    println("from=" + range.first)  // from=1
    println("to=" + range.second)   // to=100

    // Option B: with destructuring
    val (from, to) = range
    println("from=$from to=$to")    // from=1 to=100
}

Both options are valid. But in the second case, the “agreement” about the meaning of the components is moved into the names from/to, and this usually reduces the chance of mixing up the order.

Can you specify types during destructuring?

Yes, you can. Kotlin usually infers the types, but sometimes it’s useful to make the type explicit so you understand what’s going on (or so the compiler can point out an error earlier).

fun main() {
    val data: Pair<Int, String> = 7 to "days"

    val (count: Int, label: String) = data
    println("$count $label") // 7 days
}

In practice, most of the time val (count, label) = data is enough, but the ability to write the type explicitly is a good “plan B” if you’re unsure.

Triple: val (a, b, c) = triple

Triple is the same thing, just with three components. And destructuring is especially nice here because first/second/third are even harder to read, than first/second: your brain starts treating them as “first/second/third something,” rather than concrete values.

An example with an RGB color:

fun main() {
    val rgb = Triple(255, 128, 0)

    val (r, g, b) = rgb
    println("r=$r g=$g b=$b") // r=255 g=128 b=0
}

Here destructuring is not just “shorter,” it does the main thing: we removed the words first/second/third and replaced them with domain terms (r/g/b). That’s exactly why destructuring is loved in real code.

2. Skipping components with _

Now an important technique: sometimes you need a Pair or Triple as a container to “carry everything at once,” but at a specific usage site you only need part of it. You don’t want to create a variable just so it sits there as dead weight — and the compiler doesn’t want that either: it will start warning that the variable is unused.

For this, Kotlin has _ in destructuring: it means “I don’t need this component.” This is not a variable; it is specifically a placeholder.

Example:

fun main() {
    val result = "OK" to 200

    val (status, _) = result
    println(status) // OK
}

We skipped the second component (200). And it reads like an intentional decision: “I know there is a code there, but I don’t need it right now.”

_ cannot be used as a variable

A very common beginner mistake is trying to access _ later as if it were a variable name. That won’t work.

fun main() {
    val p = 3 to 4
    val (_, y) = p

    println(y)   // 4
    println(_) // not allowed: "_" is not a variable
}

This strictness is only a plus: it protects you from accidentally using something you yourself declared as “unimportant.”

_ is also useful as a hint to the reader

Sometimes beginners get the thought: “what’s wrong with val (a, b) if b isn’t needed?” There’s nothing wrong, the program will work, but for the reader of the code (including you a week later) it will be unclear: is the component actually important, just not used yet, or is it truly unnecessary? _ solves this honestly: “no, it’s not needed.”

4. How destructuring works: componentN()

Let’s figure out how all of this works — we’re programmers, after all, right? Destructuring looks like special language syntax, but in reality the compiler simply translates it into calls to special functions componentN().

The rule is simple: if an object can respond to component1(), component2() (and so on), then it can be destructured. The Kotlin specification explicitly shows that destructuring relies on these component functions, and the unpacking proceeds in component order.

Example: manually instead of destructuring

What the compiler does automatically, we can write ourselves:

fun main() {
    val p = 3 to 4

    val a = p.component1()
    val b = p.component2()

    println(a + b) // 7
}

This is not “better” than val (a, b) = p, but it’s useful to see the mechanics. Destructuring is a convenient wrapper around component calls.

A mini-diagram of what happens

If we simplify, then destructuring:

val (a, b) = pair

is roughly equivalent to this idea:

tmp = pair
a = tmp.component1()
b = tmp.component2()

And an important detail: a temporary variable tmp is created so that the expression on the right is evaluated once. This is especially noticeable with nested destructuring (when “inside” there is also a Pair), and the specification illustrates how the compiler expands this into a sequence of componentN() calls with temporary variables.

We won’t dive into complex nested variants right now (so we don’t turn the lecture into a nesting-doll circus), but the principle itself is useful to understand: destructuring is syntactic sugar, not a separate memory model.

Limitation: destructuring is a declaration, not an assignment

In Kotlin, destructuring in this form works specifically as a declaration of new variables:

val (x, y) = point

But not as “overwrite existing x and y in one line.” That is, you cannot do “destructuring assignment” like in Python — here you’ll have to assign separately or redeclare variables in a new scope (for example, inside a block { ... }).

5. Practice: “ContactCard” using Pair

Let’s carefully integrate destructuring into our training project “write small functions and print the result.” Imagine we’re making a simple console stub of a “contact card”: name and phone. For now without complex architecture and without commands — just to demonstrate the idea.

Create a Pair as a “contact” and unpack it nicely:

fun main() {
    val contact = "Ada Lovelace" to "+44 123 456"

    val (name, phone) = contact
    println("Name: $name")   // Name: Ada Lovelace
    println("Phone: $phone") // Phone: +44 123 456
}

Now let’s make a version where the phone is not needed (for example, we only print the name for a list):

fun main() {
    val contact = "Ada Lovelace" to "+44 123 456"

    val (name, _) = contact
    println("Name: $name") // Name: Ada Lovelace
}

Notice how comfortable this is to read: you explicitly show the intent — take only the name.

6. Common mistakes when destructuring Pair/Triple

Mistake #1: trying to destructure a Pair into three variables (or a Triple into two).
This is one of the most common “shape errors”: three names on the left, an object with two components on the right. The compiler can’t read your mind and will honestly say that component3() is missing or, conversely, that you are asking for too few components. Keep a simple mapping in mind: Pair is exactly two components, Triple is exactly three.

Mistake #2: using meaningless names a, b, c where the meaning matters.
Destructuring by itself does not automatically make code understandable: it only gives you a chance to name things well. If you write val (a, b) = range, the reader will still be guessing what a and b are. If these are the bounds of a range — use from/to; if these are coordinates — x/y; if these are a status and a code — status/code.

Mistake #3: destructuring for destructuring’s sake when you need only one component.
Sometimes people write val (x, _) = pair even when it’s simpler and clearer to take pair.first. Formally it’s fine, but stylistically the option that “moves less code around” usually wins. If you need one component once — take first/second/third. If the components will then be actively used in the code — destructure.

Mistake #4: forgetting that component order is a contract.
Destructuring unpacks strictly in order: the first goes into the first variable, the second into the second, and so on. It does not “understand” what you wanted. So if in one place you decided that minMax is (min, max), stick to that everywhere. Otherwise you’ll get a bug that looks like “everything works, but for some reason sometimes negative numbers become positive.”

Mistake #5: treating _ as a normal variable.
_ in destructuring means “drop this component,” not “name a variable underscore.” You cannot print it with println(_), pass it along, store it, and so on. If you suddenly realize you do need the component after all — just give it a proper name.

Mistake #6: not understanding the connection to componentN() and being scared by compiler messages.
Sometimes the compiler complains about a missing component2() or a type mismatch — and it sounds like a spell from dark magic. But behind it is a simple mechanism: destructuring = calls to componentN() in order. If you remember this connection, compiler messages become translatable: “I can’t get the second component” or “the second component is the wrong type.”

1
Task
Kotlin SELF, level 10, lesson 2
Locked
Coordinate Navigator
Coordinate Navigator
1
Task
Kotlin SELF, level 10, lesson 2
Locked
Status without code
Status without code
1
Task
Kotlin SELF, level 10, lesson 2
Locked
Average color
Average color
1
Task
Kotlin SELF, level 10, lesson 2
Locked
Pass check
Pass check
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION