Tuples
Tuples can hold between two and twenty-two items. They are instantiated by enclosing the items in parentheses, separated by commas.
val myTuple = (1, "hello", true)
This creates a tuple containing an Int, a String, and a Boolean.
Accessing Tuple Elements
Elements of a tuple are accessed using the ._n syntax, where n is the 1-based index of the element.
val number = myTuple._1 // 1
val greeting = myTuple._2 // "hello"
val flag = myTuple._3 // true
Tuple Destructuring
Scala allows "destructuring" tuples into individual variables:
val (num, greet, flg) = myTuple
After this operation, num will be 1, greet will be "hello", and flg will be true.
Using Tuples in Functions
Tuples are particularly useful for functions that need to return multiple values. Here's an example:
def minMax(values: Array[Int]): (Int, Int) = {
(values.min, values.max)
}
val limits = minMax(Array(1, 2, 3, 4, 5))
// limits is now (1, 5)
Tuples and Maps
Tuples are often used with Scala's Map collection since a map is essentially a collection of key-value pairs, and each key-value pair can be represented as a tuple:
val capitals = Map("France" -> "Paris", "Japan" -> "Tokyo")
// Adding a new key-value pair
val newCapitals = capitals + ("USA" -> "Washington D.C.")
Here, "France" -> "Paris" is syntactic sugar for creating a tuple of two elements.
Operations
| Operation | Example | Result |
|---|---|---|
| size | (1, 2, 3).size | 3 |
| head | (3 *: 4 *: 5 *: EmptyTuple).head | 3 |
| tail | (3 *: 4 *: 5 *: EmptyTuple).tail | (4, 5) |
| *: | 3 *: 4 *: 5 *: 6 *: EmptyTuple | (3, 4, 5, 6) |
| drop | (1, 2, 3).drop(2) | (3) |
| take | (1, 2, 3).take(2) | (1, 2) |
| apply | (1, 2, 3)(2) | 3 |
| splitAt | (1, 2, 3, 4, 5).splitAt(2) | ((1, 2), (3, 4, 5)) |
| zip | (1, 2, 3).zip(('a', 'b')) | ((1 'a'), (2, 'b')) |
| toList | (1, 'a', 2).toList | List(1, 'a', 2) |
| toArray | (1, 'a', 2).toArray | Array(1, '1', 2) |
| toIArray | (1, 'a', 2).toIArray | IArray(1, '1', 2) |