元組是一個不可變的對象序列。
scala> val names = ("mike", "john", "liky")
names: (String, String, String) = (mike,john,liky)
scala> names._1
res5: String = mike
scala> names._2
res6: String = john
scala> names._3
res7: String = liky
Scala中沒有如下的多值賦值方式:
scala> var name,age = "mike", 2
<console>:1: error: ';' expected but ',' found.
var name,age = "mike", 2
^
但是借助元組提供了另一種方式的多值賦值
object App {
def getProductInfo (productId :Int) :(String, Int, Date) = {
//產品名字 數量 過期日期
("biscuit", 10, new Date)
}
def main(args: Array[String]) {
val (name, count, expirationDate) = getProductInfo(1)
println(s"name: $name count:$count expiration Date:$expirationDate")
}
}