Skip to content
Tutorials Center
My learning

Topics

Lesson 71 of 134 ยท Idiomatic Kotlin

Destructuring and Component Functions

Go deeper with Kotlin destructuring: how componentN works, custom component functions, destructuring lambda parameters, the underscore, map entries, MatchResult and the pitfalls.

You have already used destructuring with pairs and data classes: val (name, age) = person. It looks like built-in syntax, but it is another operator convention: the compiler turns it into calls of functions named component1(), component2() and so on. Once you know that, a lot of things become clear: why data classes support it, why a plain class does not, why you can add destructuring to a type you do not own, and why reordering the properties of a data class can silently change the meaning of your code.

This lesson builds on Pairs, Triples and Destructuring and the operator conventions. It covers the exact translation rules, custom componentN functions, destructuring in lambdas and loops, the underscore for unused values, and the design question: when is destructuring clearer than a name, and when is it a trap?

What the compiler really does

val (a, b) = expr is shorthand for evaluating expr once and calling the component functions on it:

Kotlin
// read-only illustration of the translation
val tmp = expr
val a = tmp.component1()
val b = tmp.component2()

The right side is evaluated exactly once. Every componentN must be an operator fun (a member or an extension). Data classes generate component1(), component2(), ... for the properties of the primary constructor, in declaration order. That order is the entire contract.

Kotlin Calling the component functions yourself

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

You can take fewer components than the type has (you get the first ones), but never more. Asking for a component that does not exist is a compile error, and the message names the missing function:

Kotlin Too many components (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The compiler answers main.kt:4:21: error: destructuring of type 'Point' requires operator function 'component3()'. and underlines the initializer. The cure is to take only two components, or to add a component3() operator, which the next section shows.

Order matters: a silent pitfall

Because destructuring is positional, the names you choose on the left do not have to match the property names. That is convenient and dangerous:

Kotlin Names on the left are only labels

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The first line compiles without any warning and prints width=1080 height=1920: you named the first value height, but it is width. The same happens when someone later inserts a new property in the middle of the data class: every destructuring declaration that follows the old order still compiles, if the types fit, and now reads the wrong fields. When types are identical (two Ints or two Strings) the compiler cannot help you.

Use destructuring for small, stable, obviously ordered values: Pair, Triple, map entries, coordinates. For a data class with five properties of mixed meaning, access by name (p.city). A change to the class then breaks the code at compile time instead of silently changing behavior.

Your own component functions

A regular class gets no componentN automatically, but you can add them as members, or as extensions to a class you do not own. The standard library does exactly that for List and arrays (the first five elements) and for Map.Entry.

Kotlin Member and extension component functions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Because a list's componentN is just get(N-1), destructuring a list that is too short fails at run time, not at compile time. Here is what that looks like:

Kotlin Destructuring a short list (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The program stops with Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 2 out of bounds for length 2. When the length is not guaranteed, check it first or use getOrNull:

Kotlin Safer ways to take parts of a list

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

parseClock returns a nullable Triple; destructuring happens only after the ?: error(...) guard, so the variables are non-null.

The underscore: skip what you do not need

If you need only some components, put _ in the other slots. The underscore does not call the function and does not create a variable, so it also avoids "unused variable" warnings:

Kotlin Underscore for unused components

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Skipping component2() in the middle still works because the underscore position is skipped, not removed. The underscore works the same way in for loops and in lambda parameters.

Destructuring in lambdas and loops

In a for loop, destructuring is everywhere: for ((index, value) in list.withIndex()) and for ((key, value) in map). In a lambda, there is an important syntactic difference between two parameters and one destructured parameter:

  • { a, b -> ... } is a lambda that takes two arguments.
  • { (a, b) -> ... } is a lambda that takes one argument and destructures it.
Kotlin Two parameters versus one destructured parameter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Forgetting the parentheses is a typical mistake. pairs.map { number, word -> ... } is a compile error because map calls its lambda with one argument, a Pair:

Kotlin Missing parentheses in a lambda (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The compiler reports two errors. The first is error: argument type mismatch: actual type is '(Pair<Int, String>, ??? (Unknown type for value parameter word)) -> uninferred R ...', but '(Pair<Int, String>) -> uninferred R ...' was expected. and the second is error: cannot infer type for value parameter 'word'. Specify it explicitly. Read it as "you wrote a lambda with two parameters, but one Pair is passed". The fix is { (number, word) -> ... }. In a destructured lambda parameter you can also give each name a type: { (n: Int, w: String) -> ... }.

Returning several values

Destructuring is the idiomatic way to return more than one value from a function without inventing a class, provided the pieces are few and the meaning is obvious. Pair and Triple work; a small private data class often reads better because the property names document the result:

Kotlin Multiple return values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

MatchResult.destructured returns a small object whose component1() ... component10() are the capture groups, so you can write val (key, value) = match.destructured. The groups are not counted from the whole match; group 0 is skipped. Regular expressions have their own lesson: Regular Expressions.

Swapping, shadowing and other small tricks

A destructuring declaration creates new variables; it is not an assignment. To swap two variables you need a helper, since (a, b) = (b, a) as an assignment is not Kotlin. With also or a temporary it is short:

Kotlin Swapping and destructuring assignments

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The comment in the code matters: destructuring always declares variables, so you cannot assign into variables that already exist. A var is allowed on the left: var (a, b) = pair creates two mutable variables. Nested patterns like val ((p, q), r) = ... are not accepted by the compiler used here (they are not a stable feature), so destructure one level at a time as the example does.

Design guidance

  • Stable and small: two or three components, with an order everybody knows. Pair<Key, Value>, (x, y), (quotient, remainder).
  • Prefer names for big data classes. If a property is added in the middle, destructuring call sites change meaning.
  • Do not expose componentN casually in a public class. It freezes the property order as a binary and source contract. Data classes do this already, which is another reason to hide internal order by using normal classes for complex types.
  • Use _ generously to say "I know there is something here, I do not need it".
  • Remember val versus var: val (a, b) makes both read-only.
  • Performance: destructuring a data class costs only getter calls, with no allocation. Pair and Triple allocate an object when you create them, so returning one from a hot loop creates garbage; a data class or two separate results may be better.
  • Interop: the functions are named component1() and so on in bytecode, so Java code sees ordinary methods.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does val (a, b) = obj compile to?

    Destructuring is positional and uses component functions; the names on the left are only labels for the results.
  2. 2. Which lambda correctly receives a Pair<Int, String> and uses both parts?

    A destructured lambda parameter needs parentheses. Without them you declare two parameters and the compiler complains that the lambda gets only one.
  3. 3. What happens with val (h, m, s) = listOf("10", "30")?

    List component functions simply read by index, so the length is checked at run time, not by the compiler.
  4. 4. What does the underscore do in val (_, name) = person?

    An underscore marks an unused position in a destructuring declaration or lambda parameter list.
  5. 5. Why can destructuring a data class with several String properties be risky?

    The compiler cannot detect a swap of two values of the same type. Access by property name when a class has many or similar properties.

Summary

  • val (a, b) = x calls x.component1() and x.component2(); x is evaluated once.
  • Data classes generate componentN for primary-constructor properties in declaration order; you can add your own members or extensions.
  • Names on the left are labels only, so keep destructuring for short, stable, ordered values.
  • Taking more components than exist is a compile error; destructuring a short list fails at run time.
  • Use _ to skip components, and parentheses to destructure a single lambda parameter: { (k, v) -> ... }.
  • MatchResult.destructured, withIndex() and map entries are the everyday places you will use it.
  • Destructuring declares new variables; it cannot assign to existing ones.

Next: Smart Casts and Contracts