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

Tuples

In this page:

  1. Tuples

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")
}
🔒

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.