如何将 Scala 数组传递给 Scala vararg 方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31064753/
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
How to pass Scala array into Scala vararg method?
提问by Cherry
Consider the code below:
考虑下面的代码:
private def test(some:String*){
}
private def call () {
val some = Array("asd", "zxc")
test(some)
}
It prints expect String, found Array[String]Why? Are Scala varargs not arrays?
它打印expect String, found Array[String]为什么?Scala 可变参数不是数组吗?
Note
笔记
I found several questions on Stack Overflow about Scala varargs, but all of them are about calling Java varargs methods or about converting Scala lists to arrays.
我在 Stack Overflow 上发现了几个关于 Scala varargs 的问题,但所有这些问题都是关于调用 Java varargs 方法或关于将 Scala 列表转换为数组。
回答by Yuhuan Jiang
Append :_*to the parameter in testlike this
像这样附加:_*到参数test
test(some:_*)
And it should work as you expect.
它应该按您的预期工作。
If you wonder what that magical :_*does, please refer to this question.
如果你想知道这个魔法有什么:_*作用,请参考这个问题。
回答by Herrington Darkholme
It is simple:
很简单:
def test(some:String*){}
def call () {
val some = Array("asd", "zxc")
test(some: _*)
}

