Start learning free

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

Tuples in Scala

Lesson

TL ; DR:

A tuple keeps a few values together, like a movie's title and year. Read them with ._1 and ._2, or unpack them into variables.


val movie = ("Frozen", 2013)   // a tuple
println(movie._1)              // Frozen
println(movie._2)              // 2013

val (title, year) = movie      // unpacking
println(s"$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. A tuple keeps a few values like these in one variable.

  • ("Frozen", 2013) makes a tuple. Its type is (String, Int).
  • movie._1 is the first value, "Frozen". movie._2 is the second, 2013. They count from 1, not 0.

val (title, year) = movie unpacks the tuple into two new values. It works like for ((name, points) <- scores).

A function can return a tuple. Its return type is the tuple's type, like (Int, Int). Then return (a, b) builds it.

A tuple can't be changed. movie._2 = 2014 doesn't compile. To change a value, make a new tuple: (movie._1, 2014).

Printing a tuple 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 tuple: 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