8.33. Scala tuple

发布时间 : 2025-10-25 13:35:17 UTC      

Page Views: 9 views

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:

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 ) } } 

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

8.33.2. 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:

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() ) } } 

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:

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 ) } } 

Execute the above code, and the output is as follows:

$ scalac Test.scala $ scala Test Swapped tuples: (www.runoob.com,www.google.com) 
《地理信息系统原理、技术与方法》  97

最近几年来,地理信息系统无论是在理论上还是应用上都处在一个飞速发展的阶段。 GIS被应用于多个领域的建模和决策支持,如城市管理、区划、环境整治等等,地理信息成为信息时代重要的组成部分之一; “数字地球”概念的提出,更进一步推动了作为其技术支撑的GIS的发展。 与此同时,一些学者致力于相关的理论研究,如空间感知、空间数据误差、空间关系的形式化等等。 这恰好说明了地理信息系统作为应用技术和学科的两个方面,并且这两个方面构成了相互促进的发展过程。