Scala:将元组列表扩展为元组的可变长度参数列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10842851/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 04:12:20  来源:igfitidea点击:

Scala: Expand List of Tuples into variable-length argument list of Tuples

scalafunctional-programming

提问by forker

I'm puzzled on how to expand List/Seq/Array into variable-length argument list.

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

Given that I have test_func function accepting tuples:

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

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

Which works when I pass tuples:

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

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

From reading the Scala reference I've got strong impression that the following whould work as well:

通过阅读 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")))
                        ^

And one more desperate attempt:

还有一个绝望的尝试:

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)

How to expand List/Seq/Array into argument list?

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

Thank you in advance!

先感谢您!

回答by Prince John Wesley

You need to add :_*.

您需要添加:_*.

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!