How to pass an argument with a star to the next method?

scala> class A (s: String*) { val l: ListBuffer[String] = ListBuffer[String](s) }
<console>:8: error: type mismatch;
  found   : String*
  required: String
    class A(s: String*)  {val l: ListBuffer[String] = ListBuffer[String](s)}

Why it is not possible to pass an argument sto the apply ListBuffer [String] method, which is

def apply[A](elems: A*): CC[A] = { ... }

(Method applyof GenericCompanion.scala)

The code is ListBuffer[String]("foo", "bar")working. But it looks like I can't go through the list of string arguments from s, which is also String*.

+5
source share
1 answer

You need to tell Scala to unzip s:

ListBuffer[String](s: _*)

You also do not need explicit types:

scala> class A (s: String*) { val l = ListBuffer(s: _*) }
defined class A
+9
source

All Articles