1

你能帮我理解这种行为吗

  //Creating a tuple
  val myTuple = ("Sudipta","Deb","Switzerland",1234)
                                                  //> myTuple  : (String, String, String, Int) = (Sudipta,Deb,Switzerland,1234)
  myTuple._2                                      //> res0: String = Deb
  myTuple._4                                      //> res1: Int = 1234
  val (first, second, third, fourth) = myTuple    //> first  : String = Sudipta
                                                  //| second  : String = Deb
                                                  //| third  : String = Switzerland
                                                  //| fourth  : Int = 1234
  //val (first1, second1, _) = myTuple

现在最后一行给了我错误:

constructor cannot be instantiated to expected type;  found   : (T1, T2, T3)  required: (String, String, String, Int)

我的问题是为什么它会这样?在 Scala for Impatient Book 中是这样写的:

You can use a _ if you don’t need all components:
val (first, second, _) = t

仅供参考,如果您想查看完整代码,它在我的 GitHub 存储库中。链接:Scala 工作表

4

1 回答 1

3

您必须_为每个未使用的元组成员放置一个。

val (first1, second1, _, _) = myTuple
于 2013-09-01T14:52:01.630 回答