當需要返多重賦值例如 Strings 時, Java 的作法,
scala> ("a", "B", "C") res26: (java.lang.String, java.lang.String, java.lang.String) = (a,B,C) scala> ("a", "B", 2) res27: (java.lang.String, java.lang.String, Int) = (a,B,2) scala> ("a", 2.2, 2, true) res28: (java.lang.String, Double, Int, Boolean) = (a,2.2,2,true) 值從 1..N 計起 scala> def getInfo(x: Int) = ("Wisdom", "Fish", 22, true) getInfo: (x: Int)(java.lang.String, java.lang.String, Int, Boolean) scala> def getInfo(x: Int) = { ("Wisdom", "Fish", 22, true) } getInfo: (x: Int)(java.lang.String, java.lang.String, Int, Boolean) scala> def getInfo(x: Int) { ("Wisdom", "Fish", 22, true) } getInfo: (x: Int)Unit scala> val (a, b, c, d) = getInfo(1) a: java.lang.String = Wisdom b: java.lang.String = Fish c: Int = 22 d: Boolean = true scala> var (a, b, c, d) = getInfo(1) a: java.lang.String = Wisdom b: java.lang.String = Fish c: Int = 22 d: Boolean = true 未能滿足類型 scala> var (a, b, c) = getInfo(1) <console>:9: error: constructor cannot be instantiated to expected type; found : (T1, T2, T3) required: (java.lang.String, java.lang.String, Int, Boolean) var (a, b, c) = getInfo(1) ^ <console>:9: error: recursive value x$1 needs type var (a, b, c) = getInfo(1) ^ 存取特定值以 _N 為方式 scala> val x = getInfo(0) x: (java.lang.String, java.lang.String, Int, Boolean) = (Wisdom,Fish,22,true) scala> x._2 res29: java.lang.String = Fish Scala - Tuples 特點
或許想知道為什麼你不能像訪問List裡的元素那樣訪問元組的,就像pair(0)。那是因為List的apply方法始終返回同樣的類型,但是元組裡的 或許類型不同。_1可以有一個結果類型,_2是另外一個,諸如此類。這些_N數字是基於1的,而不是基於0的,因為對於擁有靜態類型元組的其他語言,如 Haskell和ML,從1開始是傳統的設定。 Wikipedia - Tuples在 電腦科學(特別是在程式語言和資料庫的關係模型)中,多元組通常被定義為從欄位名到特定值的有限函數。其目的和在數學中一樣,指出特定的實體或物件包含特定的部分且(或)具有特定的性質。但是,這裏的部分通過唯一的欄位名來識別,而不是通過位置,從而得到更多使用者較直觀的表示。 多元組的一個例子: ( 選手 : "Harry", 成績 : 25 ) 就是一個映射欄位名「選手」到字元串 "Harry",映射欄位名「成績」到數 25 的函數。注意,這裏各個部分的順序互不相關,所以相同的多元組也可以寫成: ( 成績 : 25, 選手 : "Harry" ) 在關係模型中,這樣的多元組是表示一個簡單命題的典型。這個例子的意思就是有一個選手的名字叫 "Harry",他的成績是 25。 在程式語言中,多元組被用來構建資料結構。
Besides val pair = (99, "Luftballons")
In the first line of this code, you create a new tuple that contains an 99
The actual type of a tuple depends upon the number and of elements it contains and the types of those elements. Thus, the type
of |
C05.入門與語法(Syntax) >