← Back to Scala Course | Chapter 6: Collections Basics | Lesson 7 of 8

Tuples

A tuple bundles a few values together, even of different kinds, like a lunch tray with a sandwich, an apple, and a juice. It is a quick way to carry several facts as one.

In this page:

  1. Tuples
Syntax
scala
val tuple = (value1, value2, value3)
tuple._1
val (a, b, c) = tuple

Tuples

A tuple groups a fixed number of values of possibly different types together, written (1, "two", 3.0), with a type like (Int, String, Double).

Elements are accessed with ._1, ._2, etc. (1-indexed, unlike most Scala collections). Tuples are convenient for returning multiple values from a function without defining a dedicated case class.

Note: Tuple field access with ._1, ._2 is 1-indexed, unlike array/list indexing which starts at 0.

Example: Tuples

markup
object Main extends App {
  val person = ("Alice", 30, true)

  println(person._1)
  println(person._2)
  println(person._3)

  val (name, age, active) = person
  println(s"$name is $age, active: $active")
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Indexing a tuple from zero, as in person._0, when tuple positions start at _1.
  2. Trying to change a tuple value like person._1 = "Bob", when tuples are immutable.
  3. Destructuring with the wrong number of variables, such as val (a, b) = person on a 3-tuple, which causes a compile error.
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.