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) = {
    //产品名字  数量 过期日期
     ("biscuit", 10, new Date)
  }
  
  def main(args: Array[String]) {
      val (name, count, expirationDate) = getProductInfo(1)
      println(s"name: $name count:$count expiration Date:$expirationDate")
  }
  
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容