问题描述
为什么从Java使用所有Scala vararg方法时,它们似乎都接受Seq变量,因此不能用作Java本机vararg方法.这是一个错误吗?
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?
例如,Buffer
具有方法def append(elems: A*): Unit
.但是在Java中,它还有另一个签名:void append(Seq<A>)
.
For instance, Buffer
has method def append(elems: A*): Unit
. But in java it has another signature: void append(Seq<A>)
.
推荐答案
这不是错误.这是一种设计选择,它支持在Scala中使用vararg而不是与Java进行互操作.例如,它允许您将List
传递到Scala varargs方法中,而不必在途中将其转换为Array
.
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.
如果您需要使用Java的Scala变量,则应该创建一些scala Seq.例如,您可以编写Java包装程序来自动创建一个数组,然后使用Predef
对象中的genericWrapArray
方法.
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.
这篇关于在Java中使用Scala vararg方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!