11

Why do all scala vararg methods, when used from java, seem to accept a Seq of variables, and can't be used as java native vararg methods. Is this a bug?

For instance, Buffer has method def append(elems: A*): Unit. But in java it has another signature: void append(Seq<A>).

F0RR
  • 1,590
  • 4
  • 16
  • 30

3 Answers3

17

If you control the scala code you can use @varargs to make it generate a java-compatible varags method, e.g. @varargs def append(elems: A*): Unit = {}

lmm
  • 17,386
  • 3
  • 26
  • 37
8

It is not a bug. It is a design choice that favors vararg use within Scala over interoperability with Java. For example, it allows you to pass a List into a Scala varargs method without having to convert it to an Array on the way.

If you need to use Scala varargs from Java, you should create some scala Seq instead. You can, for example, write a Java wrapper to get an array automatically created, and then use the genericWrapArray method from the Predef object.

Rex Kerr
  • 166,841
  • 26
  • 322
  • 407
-6

you can easily cast a Seq in varargs using :_*. For example :

val b = collection.mutable.ListBuffer.empty[Int]
b.append(List(1, 2):_*)

so this avoid code duplication in the collection API.

You can also simply use appendAll :

b.appendAll((List(1, 2))
David
  • 2,399
  • 20
  • 17