Using scala vararg methods in java

╄→гoц情女王★ 提交于 2019-11-29 09:41:42

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.

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

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