Scala Tuples
Like lists, tuples are immutable, but unlike lists, tuples can contain elements of different types.
Tuple values are formed by enclosing individual values in parentheses. For example:
val t = (1, 3.14, "Fred")
The above example defines three elements in a tuple, whose corresponding types are [Int, Double, java.lang.String].
In addition, we can also define it in the following way:
val t = new Tuple3(1, 3.14, "Fred")
The actual type of a tuple depends on the types of its elements; for example, (99, "runoob") is Tuple2[Int, String], and ('u', 'r', "the", 1, 4, "me") is Tuple6[Char, Char, String, Int, Int, String].
Currently Scala supports tuples with a maximum length of 22. For longer lengths you can use collections or extend tuples.
The elements of a tuple can be accessed by numeric indices, as in the following tuple:
val t = (4,3,2,1)
We can use t._1 to access the first element and t._2 to access the second element, as shown below:
Example
object
Test
{
def
main
(
args
:
Array
[
String
]
)
{
val
t
=
(
4
,
3
,
2
,
1
)
val
sum
=
t.
_
1 + t.
_
2 + t.
_
3 + t.
_
4
println
(
"The sum of the elements is: "
+ sum
)
}
}
The output of the code above is:
$ scalac Test.scala
$ scala Test
元素之和为: 10
Iterating over tuples
You can use the Tuple.productIterator() The method to iterate and output all elements of a tuple:
Example
object
Test
{
def
main
(
args
:
Array
[
String
]
)
{
val
t
=
(
4
,
3
,
2
,
1
)
t.
productIterator
.
foreach
{
i
=>
println
(
"Value = "
- i
)
}
}
}
The output of the code above is:
$ scalac Test.scala
$ scala Test
Value = 4
Value = 3
Value = 2
Value = 1
Converting a tuple to a string
You can use the Tuple.toString() The method combines all elements of a tuple into a string, as shown in the following example:
Example
object
Test
{
def
main
(
args
:
Array
[
String
]
)
{
val
t
=
new
Tuple3
(
1
,
"hello"
, Console
)
println
(
"The concatenated string is: "
- t.
toString
(
)
)
}
}
The output of the code above is:
$ scalac Test.scala
$ scala Test
连接后的字符串为: (1,hello,scala.Console$@4dd8dc3)
Swapping elements
You can use the Tuple.swap The method to swap the elements of a tuple. See the following example:
Example
object
Test
{
def
main
(
args
:
Array
[
String
]
)
{
val
t
=
new
Tuple2
(
"www.google.com"
,
"www.runoob.com"
)
println
(
"The swapped tuple: "
- t.
swap
)
}
}
The output of the code above is:
$ scalac Test.scala
$ scala Test
交换后的元组: (www.runoob.com,www.google.com)
Scala Collections