Reputation: 1506
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?
Upvotes: 3
Views: 964
Reputation: 6242
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).
Upvotes: 3