Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using scala vararg methods in java

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>).

like image 244
F0RR Avatar asked Nov 29 '11 10:11

F0RR


2 Answers

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 = {}

like image 158
lmm Avatar answered Oct 12 '22 18:10

lmm


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.

like image 34
Rex Kerr Avatar answered Oct 12 '22 17:10

Rex Kerr