Scala 元組與多值賦值

元組是一個不可變的對象序列。

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) = {
    //產(chǎn)品名字  數(shù)量 過期日期
     ("biscuit", 10, new Date)
  }
  
  def main(args: Array[String]) {
      val (name, count, expirationDate) = getProductInfo(1)
      println(s"name: $name count:$count expiration Date:$expirationDate")
  }
  
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容