TExcelTAD
Home › Kotlin › Kotlin Destructuring

Kotlin Destructuring

Destructuring declarations unpack an object into several variables in one line: val (name, age) = person. They make code that works with pairs, map entries and data classes much more readable.

Destructuring a data class

kotlin · try it yourself
data class Person(val name: String, val age: Int, val city: String)

fun main() {
    val person = Person("Aiko", 31, "Osaka")
    val (name, age, city) = person
    println("$name ($age) lives in $city")
}
Aiko (31) lives in Osaka

Destructuring is positional: the first variable gets the first constructor property, and so on. The variable names don't have to match the property names — but it's wise to keep them the same to avoid confusion.

How it works: componentN

val (a, b) = obj compiles to val a = obj.component1(); val b = obj.component2(). Data classes generate these functions automatically. Pair, Triple, map entries and lists (up to five elements) have them too.

kotlin · try it yourself
fun main() {
    val (x, y) = Pair(3, 4)
    val (r, g, b) = Triple(255, 128, 0)
    val (first, second, third) = listOf("gold", "silver", "bronze", "wood")
    println("x=$x y=$y")
    println("rgb($r, $g, $b)")
    println("$first, $second, $third")
}
x=3 y=4
rgb(255, 128, 0)
gold, silver, bronze

Skipping components

Use _ for values you don't need:

kotlin · try it yourself
data class Reading(val sensor: String, val value: Double, val unit: String)

fun main() {
    val r = Reading("T-01", 21.5, "°C")
    val (_, value, unit) = r
    println("$value $unit")
}
21.5 °C

Returning several values from a function

A function can return a data class or a Pair, and the caller destructures it — a clean replacement for "out parameters":

kotlin · try it yourself
data class Stats(val min: Int, val max: Int, val average: Double)

fun stats(values: List<Int>) = Stats(values.min(), values.max(), values.average())

fun divide(a: Int, b: Int): Pair<Int, Int> = a / b to a % b

fun main() {
    val (lo, hi, avg) = stats(listOf(4, 8, 15, 16, 23, 42))
    println("min=$lo max=$hi avg=$avg")

    val (quotient, remainder) = divide(17, 5)
    println("17 / 5 = $quotient remainder $remainder")
}
min=4 max=42 avg=18.0
17 / 5 = 3 remainder 2

Tip: Pair is fine for quick, local results. For anything that's part of your public API, a small data class with meaningful property names is clearer than first and second.

In loops and lambdas

Destructuring shines when iterating over maps, withIndex() or lists of pairs:

kotlin · try it yourself
fun main() {
    val capitals = mapOf("France" to "Paris", "Japan" to "Tokyo", "Peru" to "Lima")
    for ((country, capital) in capitals) {
        println("$capital is the capital of $country")
    }

    val runners = listOf("Ola", "Bea", "Tim")
    for ((place, runner) in runners.withIndex()) {
        println("#${place + 1} $runner")
    }

    val totals = listOf("a" to 2, "b" to 5).map { (key, n) -> "$key=${n * 10}" }
    println(totals)
}
Paris is the capital of France
Tokyo is the capital of Japan
Lima is the capital of Peru
#1 Ola
#2 Bea
#3 Tim
[a=20, b=50]

Note the parentheses in lambdas: { (key, n) -> … } destructures one parameter, while { key, n -> … } would mean two parameters.

Your own componentN functions

Any class can support destructuring by declaring operator fun componentN():

kotlin · try it yourself
class Range2D(val width: Int, val height: Int) {
    operator fun component1() = width
    operator fun component2() = height
}

fun main() {
    val (w, h) = Range2D(1920, 1080)
    println("${w}x$h = ${w * h} pixels")
}
1920x1080 = 2073600 pixels

Watch out: order matters

Because destructuring is by position, reordering properties in a data class silently changes what each variable receives. Destructuring a list with fewer elements than variables throws an IndexOutOfBoundsException. Use destructuring for small, stable shapes.

Test yourself

What does val (a, b) = Pair("x", 9) assign to b?

  1. "x"
  2. 9
  3. Pair
  4. null

How do you skip a component you don't need?

  1. Leave it empty: (a, , c)
  2. Use an underscore: (a, _, c)
  3. Use null
  4. You can't

Which functions make destructuring work?

  1. get1(), get2()
  2. component1(), component2() ...
  3. first(), second()
  4. destructure()