23

我对如何将 List/Seq/Array 扩展为可变长度参数列表感到困惑。

鉴于我有 test_func 函数接受元组:

scala> def test_func(t:Tuple2[String,String]*) = println("works!")
test_func: (t: (String, String)*)Unit

当我传递元组时哪个有效:

scala> test_func(("1","2"),("3","4"))
works!

通过阅读 Scala 参考资料,我有一个强烈的印象,即以下内容也可以工作:

scala> test_func(List(("1","2"),("3","4")))
<console>:9: error: type mismatch;
 found   : List[(java.lang.String, java.lang.String)]
 required: (String, String)
              test_func(List(("1","2"),("3","4")))
                        ^

还有一次绝望的尝试:

scala> test_func(List(("1","2"),("3","4")).toSeq)
<console>:9: error: type mismatch;
 found   : scala.collection.immutable.Seq[(java.lang.String, java.lang.String)]
 required: (String, String)
              test_func(List(("1","2"),("3","4")).toSeq)

如何将 List/Seq/Array 扩展为参数列表?

先感谢您!

4

1 回答 1

49

您需要添加:_*.

scala> test_func(List(("1","2"),("3","4")):_*)
works!
scala> test_func(Seq(("1","2"),("3","4")):_*)
works!
scala> test_func(Array(("1","2"),("3","4")):_*)
works!
于 2012-06-01T00:11:34.833 回答