Scala tuple
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 t._1
access the first element t._2
access the second element, as follows:
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 )
}
}
Execute the above code, and the output is as follows:
$ scalac Test.scala
$ scala Test
The sum of elements is: 10
Iterative tuple
You can use Tuple.productIterator()
method to iterate over all the elements of the output tuple
Example
object Test {
def main(args: Array[String]) {
val t = (4,3,2,1)
t.productIterator.foreach{ i =>println("Value = " + i )}
}
}
Execute the above code, and the output is as follows:
$ scalac Test.scala
$ scala Test
Value = 4
Value = 3
Value = 2
Value = 1
Tuple to string
You can use it. Tuple.toString()
method combines all the elements of the tuple into a single string, as shown in the following example:
Example
object Test {
def main(args: Array[String]) {
val t = new Tuple3(1, "hello", Console)
println("The connected string is: " + t.toString() )
}
}
Execute the above code, and the output is as follows:
$ scalac Test.scala
$ scala Test
The connected string is: (1,hello,scala.Console$@4dd8dc3)
Element exchange
You can use Tuple.swap
method to exchange tuple elements. The following is an example:
Example
object Test {
def main(args: Array[String]) {
val t = new Tuple2("www.google.com", "www.runoob.com")
println("Swapped tuples: " + t.swap )
}
}
Execute the above code, and the output is as follows:
$ scalac Test.scala
$ scala Test
Swapped tuples: (www.runoob.com,www.google.com)