如何将 Scala 数组传递给 Scala vararg 方法?

考虑下面的代码:

private def test(some:String*){


}


private def call () {
val some = Array("asd", "zxc")
test(some)
}

它打印 expect String, found Array[String]为什么? Scala 变量不是数组吗?

注意

我在 Stack Overflow 上发现了一些关于 Scala varargs 的问题,但是它们都是关于调用 Java varargs 方法或者关于将 Scala 列表转换为数组的。

41199 次浏览

Append :_* to the parameter in test like this

test(some:_*)

And it should work as you expect.

If you wonder what that magical :_* does, please refer to this question.

It is simple:

def test(some:String*){}


def call () {
val some = Array("asd", "zxc")
test(some: _*)
}

Starting Scala 2.13.0, if you use some: _*, you will get this warning:

Passing an explicit array value to a Scala varargs method is deprecated (since 2.13.0) and will result in a defensive copy; Use the more efficient non-copying ArraySeq.unsafeWrapArray or an explicit toIndexedSeq call

As suggested, use scala.collection.immutable.ArraySeq.unsafeWrapArray:

unsafeWrapArray(some):_*

Also, another warning that you should be getting is this one

procedure syntax is deprecated: instead, add : Unit = to explicitly declare test's return type

To fix that, add = just before function's opening bracket:

def test(some:String*) = {