Using scala vararg methods in java

梦想的初衷 提交于 2019-11-28 03:06:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!