Skip to content
Tutorials Center
My learning

Topics

Lesson 43 of 134 ยท Collections

Pairs, Triples and Destructuring

Learn Kotlin Pair and Triple, the to function, destructuring declarations, componentN functions, underscores for unused values and looping over maps, with runnable examples.

Sometimes a function needs to hand back two values: the smallest and largest number in a list, a name and an age, the quotient and the remainder of a division. Kotlin has no tuples built into the syntax, but its standard library gives you two small classes for the job, Pair and Triple, and a language feature called destructuring that unpacks them into separate variables in one line.

You have already met Pair without naming it: every "France" to "Paris" in a map builds one. This lesson shows what a pair really is, how destructuring works for pairs, data classes and map entries, which classes are allowed to be destructured, and when a real class beats a Pair.

Pair and the to function

A Pair<A, B> holds exactly two values, called first and second. The to function is an infix function that creates one, so "x" to 1 reads nicely and means the same as Pair("x", 1).

Kotlin Creating and reading pairs

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.

Printing a pair shows (Ada, 36). Two pairs are equal when both parts are equal, because Pair is a data class (you will learn those in Data Classes). That is why a == Pair("Ada", 36) prints true, and why copy(second = 37) works. toList() turns a pair of the same type into a two-element list; here the two parts have different types, so the list holds Any.

A pair is immutable. There is no way to change first after creation: you make a new pair.

Triple

When two values are not enough, Triple<A, B, C> has first, second and third. There is nothing beyond three; if you need four, you need a class.

Kotlin A Triple as a quick return value

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 output is (4, 42, 18.0) and then the labelled line. Notice the downside already: result.first, result.second and result.third say nothing about what the values mean. Destructuring fixes that problem for the caller.

Destructuring declarations

A destructuring declaration creates several variables from one object in a single statement:

Kotlin Destructuring pairs and triples

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.

val (name, age) = pair declares two variables at once, with the types taken from the pair (String and Int). Use val or var for the whole group, as in var (x, y). The divmod extension (see Extension Functions) shows the classic use: a function returns two results and the caller names them right away.

What the compiler does

Destructuring is not magic, it is a shortcut. The line

Kotlin
val (name, age) = person

is translated into

Kotlin
val name = person.component1()
val age = person.component2()

Any type that has operator functions called component1(), component2(), and so on, can be destructured. Pair has two of them, Triple has three, data classes get one per primary-constructor property, and Map.Entry has component1() for the key and component2() for the value. The number of variables you declare must not exceed the number of component functions available. You may declare fewer, though.

Kotlin Too many variables (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 rejects this with main.kt:2:21: error: destructuring of type 'Pair<String, String>' requires operator function 'component3()'. Always read the message: it names the missing function, which tells you exactly what destructuring needs.

Skipping values with an underscore

You often need only some of the values. Put an underscore in the position you do not want and no variable is created for it:

Kotlin Unused values with underscore

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 underscore avoids "unused variable" warnings and tells the reader the value is ignored on purpose. Note that destructuring is positional: (x, _, z) takes the first and third components regardless of their names. That is convenient but also the main danger, as you will see below.

Destructuring data classes

A data class automatically gets one componentN() function per property in its primary constructor, in declaration order. So any data class can be unpacked:

Kotlin Destructuring a data class

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.

Destructuring also works in a for loop header, as above. The danger is the order: if someone later reorders the properties of User, every destructuring site silently gets different values (a String swapped for an Int would fail to compile, but two String properties swapped would not). For classes with several properties of the same type, prefer reading user.name.

Writing your own componentN functions

An ordinary class can opt in by declaring operator fun component1() and friends. This is rare for your own classes (a data class is usually the better choice) but handy for adding destructuring to a type you do not own, by using extension functions:

Kotlin Custom 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.

The first component is 26.85 degrees Celsius and the second 80.33 Fahrenheit, and "kotlin" unpacks into k and n. Only the operator modifier makes a function usable for destructuring: a plain function named component1 would not work. More about this in Destructuring and Component Functions.

Looping over maps

Iterating a map gives you Map.Entry objects. Because Map.Entry has component1() (key) and component2() (value) in the standard library, a destructuring loop is the idiomatic way to walk through a map:

Kotlin Destructuring map entries

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.

Look at the parentheses in lambdas: { (name, score) -> ... } destructures the single entry parameter. Without the inner parentheses, { name, score -> ... } would declare a lambda with two parameters, which is a different thing and does not match forEach on a map entry (the Java-style forEach { k, v -> } exists for maps, but the parentheses form works everywhere). The best value prints as Ana=91, because an entry prints as key=value.

Destructuring also works on List: val (first, second) = listOf(1, 2, 3) reads the first two elements through component1() and component2() (lists support up to five). It throws an exception when the list is too short, so use it only when you are sure of the size.

Pairs everywhere: zip, partition, associate

Many standard functions already return pairs, and destructuring makes them pleasant to use:

Kotlin Standard functions that return pairs

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.

partition splits a collection into the elements that match and those that do not, zip pairs elements up by position, and unzip does the opposite. You saw zip and partition in Collection Transformations.

When a Pair is the wrong choice

Pair and Triple are fine for short-lived, local results: a private helper's return value, an intermediate step in a pipeline. They become a problem when they leak into your public design, for three reasons:

  • No names. Pair<Int, Int> could be (width, height), (min, max) or (row, column). The reader has to guess.
  • No type safety between meanings. Two different Pair<Int, Int> values with different meanings can be mixed up without a compiler error.
  • No room to grow. Adding a third value changes every caller.

A data class costs one line and fixes all three:

Kotlin From a Pair to a data class

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 keep destructuring with the class version, but now the type documents the meaning, and area can live next to the data. A good rule: use Pair for a result that stays inside one function or one file; use a data class once the value crosses a module boundary or has more than a couple of fields.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

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

    A destructuring declaration is a shortcut for calling component1(), component2() and so on, so any type with those operator functions can be destructured.
  2. 2. Which line correctly ignores the middle value of a Triple?

    The underscore marks a component you do not need, so no variable is created for it. Leaving it out would shift the positions.
  3. 3. In a lambda over a map, which parameter list destructures each entry into key and value?

    The inner parentheses destructure a single entry parameter. Without them the lambda declares two separate parameters.
  4. 4. Why is a Pair<Int, Int> a poor return type for a public API?

    first and second say nothing about the meaning, and different pairs of the same types can be mixed up. A small data class gives the values names and a distinct type.
  5. 5. How many values does a data class with three primary-constructor properties provide for destructuring?

    The compiler generates component1() to component3() for the primary-constructor properties in the order they are declared.

Summary

  • Pair(first, second) and Triple(first, second, third) hold two or three values; a to b creates a pair. Both are immutable data classes.
  • val (x, y) = value calls component1(), component2(), ... and works for pairs, triples, data classes and map entries.
  • Use _ for components you do not need; use (k, v) in for loops and lambdas to walk through maps.
  • Destructuring is by position, not by name, so reordering properties can break it silently.
  • Prefer a small data class over Pair when the value is public, has a clear meaning or may grow.

Next: Classes and Properties