Scala tuple
And lists, tuples is immutable, but the list is different from a tuple can contain different types of elements.
Value tuple is contained by a single value in parentheses constitution. E.g:
val t = (1, 3.14, "Fred")
Examples of the above three elements are defined in the tuple corresponding to the type are [Int, Double, java.lang.String].
In addition, we can also be defined using the above method:
val t = new Tuple3(1, 3.14, "Fred")
The actual tuple type depends on the type of its elements, such as (99, "w3big") is Tuple2 [Int, String]. ( 'U', 'r', "the", 1, 4, "me") is Tuple6 [Char, Char, String, Int, Int, String].
Currently the maximum tuple length Scala support is 22. For greater lengths you can use the collection or extension tuples.
Access tuple elements can be numeric index, as a tuple:
val t = (4,3,2,1)
We can use the first element t._1 access, t._2 access the second element, as follows:
object Test { def main(args: Array[String]) { val t = (4,3,2,1) val sum = t._1 + t._2 + t._3 + t._4 println( "元素之和为: " + sum ) } }
Implementation of the above code, the output is:
$ scalac Test.scala $ scala Test 元素之和为: 10
Iterative tuple
You can useTuple.productIterator () method to iterate over all the elements of the output tuples:
object Test { def main(args: Array[String]) { val t = (4,3,2,1) t.productIterator.foreach{ i =>println("Value = " + i )} } }
Implementation of the above code, the output is:
$ scalac Test.scala $ scala Test Value = 4 Value = 3 Value = 2 Value = 1
Tuple into a string
You can useTuple.toString () method combines all the elements of the tuple into a string, examples are as follows:
object Test { def main(args: Array[String]) { val t = new Tuple3(1, "hello", Console) println("连接后的字符串为: " + t.toString() ) } }
Implementation of the above code, the output is:
$ scalac Test.scala $ scala Test 连接后的字符串为: (1,hello,scala.Console$@4dd8dc3)
Switching element
You can use the method toTuple.swap exchange element of the tuple.The following examples:
object Test { def main(args: Array[String]) { val t = new Tuple2("www.google.com", "www.w3big.com") println("交换后的元组: " + t.swap ) } }
Implementation of the above code, the output is:
$ scalac Test.scala $ scala Test 交换后的元组: (www.w3big.com,www.google.com)