Home > Articles

This chapter is from the book

4.8 Tuples

Maps are collections of key/value pairs. Pairs are the simplest case of tuples—aggregates of values of different types.

A tuple value is formed by enclosing individual values in parentheses. For example,

(1, 3.14, "Fred")

is a tuple of type

(Int, Double, String)

If you have a tuple, say,

val t = (1, 3.14, "Fred")

then you can access its components as t(0), t(1), and t(2).

As long as the index value is an integer constant, the types of these expressions are the component types:

val second = t(1) // second has type Double

If the index is variable, the type of t(n) is the common supertype of the elements:

var n = 1
val component = t(n) // component has type Any

Often, it is easiest to use the “destructuring” syntax to get at the components of a tuple:

val (first, second, third) = t // Sets first to 1, second to 3.14, third to "Fred"

You can use an _ if you don’t need all components:

val (first, second, _) = t

You can concatenate tuples with the ++ operator:

("x", 3) ++ ("y", 4) // Yields ("x", 3, "y", 4)

Tuples are useful for functions that return more than one value. For example, the partition method of the StringOps class returns a pair of strings, containing the characters that fulfill a condition and those that don’t:

"New York".partition(_.isUpper) // Yields the pair ("NY", "ew ork")

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.