Start learning free

LESSON 264 OF 677 · PAIRS, SORTING & BUILT-INS

Pairs in Kotlin

Lesson

TL ; DR:

A Pair keeps two values together, like a movie's title and year. Read them with .first and .second, or unpack them into variables.


val movie = Pair("Frozen", 2013)   // the same as "Frozen" to 2013
println(movie.first)               // Frozen
println(movie.second)              // 2013

val (title, year) = movie          // unpacking
println("$title $year")            // Frozen 2013


Full lesson:

Some values belong together. A movie has a title and a year. A point has an x and a y. Kotlin keeps two values like these in a Pair.

  • Pair("Frozen", 2013) makes a pair. Its type is Pair<String, Int>.
  • "Frozen" to 2013 makes the same pair. You have used to in mutableMapOf("Ana" to 12).
  • movie.first is the first value, "Frozen". movie.second is the second, 2013.

val (title, year) = movie unpacks the pair into two new variables. It works like for ((name, points) in scores).

A function can return a pair. Its return type is the pair's type, like Pair<Int, Int>.

A pair can't be changed. first and second are vals. To change one, make a new pair: movie.copy(second = 2014).

Pair is a data class, so printing it shows its values: (Frozen, 2013).


Your task

Rex the dog went for a long walk. pet holds his name and his age.

First, make splitTime return its pair: the whole hours and the minutes left.

Then unpack pet into name and age.

Last, call splitTime(135). Unpack its result into hours and mins.

The code already prints the three lines.

Expected output:

Rex
Rex is 4
Rex walked 2 h 15 min
STEP 1 OF 3
    Ctrl + Enter to check