如何使用Scala varargs从Java代码 [英] How to use Scala varargs from Java code
问题描述
有很多关于从Scala代码调用Java varargs的文章,但是我可以找到相反的方法是这个问题:在java中使用scala vararg方法,没有任何具体示例。
There are plenty of articles on calling Java varargs from Scala code, but the only thing I could find the opposite way round was this question: Using scala vararg methods in java, which doesn't have any concrete examples.
从一些Java代码中使用 scala.Console
,因为 java.io.Console
无法在Eclipse,而Scala一个。但我不能得到方法
I'm trying to use scala.Console
from some Java code, for the reason that java.io.Console
doesn't work in Eclipse, whereas the Scala one does. But I cannot get the method
def readLine (text: String, args: Any*): String
工作,因为它似乎期待一个 scala.collection.Seq [Any]
第二个参数,我没有看到如何在Java中创建 Seq
。如何解决这个问题?
to work because it seems to be expecting a scala.collection.Seq[Any]
for the second argument, and I don't see how to create a Seq
in Java. How can I work around this?
我试过的东西:
1)使用null
// Java
String s = scala.Console.readLine("Enter text: ", null);
- 获得 NullPointerException
2)使用替换
null
scala.collection.Seq.empty / code>,但javac报告所有类型的错误,如 Seq
没有空
方法。
2) Replacing the null
with scala.collection.Seq.empty()
, but javac reports all sorts of errors such as Seq
not having an empty
method.
3)使用 scala.collection.immutable $中的
Nil
c $ c>包对象,但是语法建议这里,这将是 scala.collection.immutable.package $ Nil $ .MODULE $
,但是无法解决。
3) Using the Nil
object in the scala.collection.immutable
package object, but the syntax suggested here, which would be scala.collection.immutable.package$Nil$.MODULE$
, but that can't be resolved.
当然,我可以使用不带varargs的 readLine()
方法,太容易了。
Of course I could just use the readLine()
method that doesn't take varargs, but that would be too easy.
推荐答案
您可以使用:
scala.collection.Seq$.MODULE$.empty();
从Java代码创建一个空序列。否则,您可以使用:
from Java code to create an empty sequence. Otherwise, you can use:
new scala.collection.mutable.ArrayBuffer();
创建一个空数组缓冲区,然后可以添加元素并将其用作Scala的参数vararg方法。
to create an empty array buffer into which you can then add elements and use it as an argument to Scala vararg methods.
否则,如果你使用vararg方法设计一个要从Java代码中使用的Scala库,那么使用 varargs
注释。它将生成一个Java版本的方法,它接受一个数组而不是
Seq
。
Otherwise, if you design a Scala library with vararg methods which you want to use from Java code, then use the varargs
annotation. It will generate a Java version of the method which takes an array instead of a Seq
.
scala> class A {
| @annotation.varargs def foo(x: Int*) { println(x) }
| }
defined class A
scala> println(classOf[A].getMethods.toList)
List(public void $line1.$read$$iw$$iw$A.foo(scala.collection.Seq), public void $line1.$read$$iw$$iw$A.foo(int[]), ...)
反射表明,有两个方法 foo
的生成 - 一个需要一个 Seq [Int]
int []
。
Above, reflection shows that there are 2 versions of method foo
generated - one that takes a Seq[Int]
and another which takes an int[]
.
这篇关于如何使用Scala varargs从Java代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!