English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Like lists, tuples are also immutable, but unlike lists, tuples can contain elements of different types.
The value of a tuple is composed by enclosing individual values in parentheses. For example:
val t = (1, 3.14, "Fred")
The above examples define three elements in the tuple, with corresponding types [Int, Double, java.lang.String].
In addition, we can also define in the following way:
val t = new Tuple3(1, 3.14, "Fred")
The actual type of a tuple depends on the type of its elements, for example (99, "w3codebox") is Tuple2[Int, String]. ('u', 'r', "the", 1, 4, "me") is Tuple6[Char, Char, String, Int, Int, String].
Currently, Scala supports the maximum length of tuples as 22. For greater lengths, you can use a set or extend the tuple.
Accessing elements of a tuple can be done through numeric indices, as in the following tuple:
val t = (4,3,2,1)
We can use t._1 Access the first element, t._2 Access the second element as shown below:
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 of elements is: " + sum ) } }
Execute the above code, the output result is:
$ scalac Test.scala $ scala Test Sum of elements is: 10
You can use Tuple.productIterator() methods to iterate and output all elements of a tuple:
object Test { def main(args: Array[String]) { val t = (4,3,2,1) t.productIterator.foreach{ i =>println("Value = " + i )} } }
Execute the above code, the output result is:
$ scalac Test.scala $ scala Test Value = 4 Value = 3 Value = 2 Value = 1
You can use Tuple.toString() methods that combine all elements of a tuple into a single string, as shown in the following example:
object Test { def main(args: Array[String]) { val t = new Tuple3(1, "hello", Console) println("The concatenated string is: " + t.toString() ) } }
Execute the above code, the output result is:
$ scalac Test.scala $ scala Test 1,hello,scala.Console$@4dd8dc3)
You can use Tuple.swap methods to swap the elements of tuples. Here is an example:
object Test { def main(args: Array[String]) { val t = new Tuple2("www.google.com", "www.oldtoolbag.com") println("Swapped tuple: " + t.swap ) } }
Execute the above code, the output result is:
$ scalac Test.scala $ scala Test Swapped tuple: (www.oldtoolbag.com,www.google.com)