如何在 Java 代码中使用 Scala 可变参数

2022-01-11 00:00:00 console scala java scala-java-interop

有很多关于从 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] 作为第二个参数,我不知道如何创建一个 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(),但是javac报Seq等各种错误没有 empty 方法.

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 对象,但语法建议 这里,这将是 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.

当然我可以只使用不带可变参数的 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 可变参数方法的参数.

to create an empty array buffer into which you can then add elements and use it as an argument to Scala vararg methods.

否则,如果您设计一个带有可变参数方法的 Scala 库,并且您想从 Java 代码中使用这些方法,那么请使用 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[]), ...)

上面,反射显示生成了 2 个版本的方法 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[].

相关文章