问题
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>)
.
回答1:
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.
回答2:
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 = {}
回答3:
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))
来源:https://stackoverflow.com/questions/8309480/using-scala-vararg-methods-in-java