How to pass Scala array into Scala vararg method?

浪子不回头ぞ 提交于 2019-11-26 12:38:58

问题


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?

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.


回答1:


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.




回答2:


It is simple:

def test(some:String*){}

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


来源:https://stackoverflow.com/questions/31064753/how-to-pass-scala-array-into-scala-vararg-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!