3

If we pass in a list to a method that takes a variable number of arguments it works.

val testList = List("a", "b", "c")

def testMethod(str: String*): Seq[String] = str

testMethod(testList) // outputs WrappedArray(List("a", "b", "c"))

But if we pass in a list to a class constructor that takes a variable number of arguments, we get a type error.

val testList = List("a", "b", "c")

class TestClass(str: String*)

val t = new TestClass(testList)

// error: type mismatch

// found: List[String]

// required: [String]

Any idea how we can fix this?

hollow7
  • 1,506
  • 1
  • 12
  • 20

1 Answers1

3

It's not working in neither case (note the unwanted WrappedArray in the first case). In order to pass a sequence as a variable-argument list, you need to treat it as such. The syntax for it is the same. In the first case:

testMethod(testList: _*)

and in the second case:

val t = new testClass(testList: _*)

You can interpret this notation in a similar fashion of variable-arguments syntax, the only difference being that here the type is not explicitly stated (underscore is used instead).

ale64bit
  • 6,232
  • 3
  • 24
  • 44