Like lists, tuples are immutable, but unlike lists, tuples can contain different types of elements.
The values of tuples are formed by enclosing individual values in parentheses. For example:
val t = (1, 3.14, "Fred")
The above example defines three elements in the tuple, and the correspondingtypes are
[Int,
Double,
java.lang.String]
.
In addition, we can also define it in the following ways:
val t = new Tuple3(1, 3.14, "Fred")
The actual type of a tuple depends on the type of its element, for example, (99, “runoob”) is
Tuple2[Int,
String]
.
('u',
'r',
"the",
1,
4,
"me")
for
Tuple6[Char,
Char,
String,
Int,
Int,
String]
.
Currently, the maximum tuple length supported by Scala is 22. You can use collections or extended tuples for larger lengths.
The elements that access the tuple can be indexed numerically, as follows:
val t = (4,3,2,1)
We can use Execute the above code, and the output is as follows: You can use Execute the above code, and the output is as follows: You can use it. Execute the above code, and the output is as follows: You can use Execute the above code, and the output is as follows:
t._1
access the first element
t._2
access the second element, as follows: 8.33.1. 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 elements is: " + sum )
}
}
$ scalac Test.scala
$ scala Test
The sum of elements is: 10
Iterative tuple #
Tuple.productIterator()
method to iterate over all the elements of the output tuple 8.33.2. Example #
object Test {
def main(args: Array[String]) {
val t = (4,3,2,1)
t.productIterator.foreach{ i =>println("Value = " + i )}
}
}
$ scalac Test.scala
$ scala Test
Value = 4
Value = 3
Value = 2
Value = 1
Tuple to string #
Tuple.toString()
method combines all the elements of the tuple into a single string, as shown in the following example: 8.33.3. Example #
object Test {
def main(args: Array[String]) {
val t = new Tuple3(1, "hello", Console)
println("The connected string is: " + t.toString() )
}
}
$ scalac Test.scala
$ scala Test
The connected string is: (1,hello,scala.Console$@4dd8dc3)
Element exchange #
Tuple.swap
method to exchange tuple elements. The following is an example: 8.33.4. Example #
object Test {
def main(args: Array[String]) {
val t = new Tuple2("www.google.com", "www.runoob.com")
println("Swapped tuples: " + t.swap )
}
}
$ scalac Test.scala
$ scala Test
Swapped tuples: (www.runoob.com,www.google.com)