Scala Tuple

Scala 集合Scala Collections

Like lists, tuples are immutable, but unlike lists, tuples can contain elements of different types.

A tuple value is formed by enclosing individual values in parentheses. For example:

val t = (1, 3.14, "Fred")  

The above example defines three elements in the tuple, with corresponding types of [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, "example") 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 larger lengths, you can use collections or extend tuples.

You can access the elements of a tuple by numeric index, like 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 elements is: "  + sum )
   }
}

After executing the above code, the output result is:

$ scalac Test.scala 
$ scala Test
元素之和为: 10

Iterating over a Tuple

You can useTuple.productIterator()method to iterate over and output all elements of the tuple:

Example

object Test {
   def main(args: Array[String]) {
      val t = (4,3,2,1)
     
      t.productIterator.foreach{ i =>println("Value = " + i )}
   }
}

After executing the above code, the output result is:

$ scalac Test.scala 
$ scala Test
Value = 4
Value = 3
Value = 2
Value = 1

Converting a Tuple to a String

You can useTuple.toString()method to combine all elements of the tuple into a single string, as in the example below:

Example

object Test {
   def main(args: Array[String]) {
      val t = new Tuple3(1, "hello", Console)
     
      println("The concatenated string is: " + t.toString() )
   }
}

After executing the above code, the output result is:

$ scalac Test.scala 
$ scala Test
连接后的字符串为: (1,hello,scala.Console$@4dd8dc3)

Swapping Elements

You can useTuple.swapmethod to swap the elements of the tuple. As in the example below:

Example

object Test {
   def main(args: Array[String]) {
      val t = new Tuple2("www.google.com", "www.example.com")
     
      println("Tuple after swapping: " + t.swap )
   }
}

After executing the above code, the output result is:

$ scalac Test.scala 
$ scala Test
交换后的元组: (www.example.com,www.google.com)

Scala 集合Scala Collections

Other Extensions