How to pass Scala array into Scala vararg method?

ArraysScalaVariadic Functions

Arrays Problem Overview


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.

Arrays Solutions


Solution 1 - Arrays

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.

Solution 2 - Arrays

It is simple:

def test(some:String*){}

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

Solution 3 - Arrays

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*) = {

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCherryView Question on Stackoverflow
Solution 1 - ArraysYuhuan JiangView Answer on Stackoverflow
Solution 2 - ArraysHerrington DarkholmeView Answer on Stackoverflow
Solution 3 - ArraysSaurav SahuView Answer on Stackoverflow