4.8 Tuples
Maps are collections of key/value pairs. Pairs are the simplest case oftuples—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 ast(0),t(1), andt(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 oft(n)is the common supertype of the elements:
var n = 1val 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_如果你不需要所有的组件:
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, thepartitionmethod of theStringOpsclass 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")