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:
Syntax
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
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")
}
Login to try C/C++/Java/PHP code in the editor
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
- Indexing a tuple from zero, as in
person._0, when tuple positions start at_1. - Trying to change a tuple value like
person._1 = "Bob", when tuples are immutable. - Destructuring with the wrong number of variables, such as
val (a, b) = personon a 3-tuple, which causes a compile error.
🔒
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: