将 Java 数组传递给 Scala

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3940699/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 02:30:35  来源:igfitidea点击:

Passing Java array to Scala

javascalascala-2.8

提问by halfwarp

Although I've been using Scala for a while and have mixed it with Java before, I bumped on a problem.

尽管我已经使用 Scala 一段时间并且之前将它与 Java 混合使用,但我还是遇到了一个问题。

How can I pass a Java array to Scala? I know that the other way around is fairly straightforward. Java to Scala is not so however.

如何将 Java 数组传递给 Scala?我知道反过来说是相当简单的。然而,Java 到 Scala 并非如此。

Should I declare my method in Scala?

我应该在 Scala 中声明我的方法吗?

Here is a small example of what I'm trying to achieve:

这是我试图实现的一个小例子:

Scala:

斯卡拉:

def sumArray(ar: Array[Int]) = ...

Java:

爪哇:

RandomScalaClassName.sumArray(new int[]{1,2,3});

Is this possible?

这可能吗?

回答by Kevin Wright

absolutely!

绝对地!

The Array[T]class in Scala is mapped directlyto the Java type T[]. They both have exactly the same representation in bytecode.

Array[T]Scala 中的类直接映射到 Java 类型T[]。它们在字节码中具有完全相同的表示形式。

At least, this is the case in 2.8. Things were a little different in 2.7, with lots of array boxing involved, but ideally you should be working on 2.8 nowadays.

至少,在 2.8 中是这样。2.7 中的情况略有不同,涉及很多数组装箱,但理想情况下,您现在应该在 2.8 上工作。

So yes, it'll work exactly as you've written it.

所以是的,它会像你写的那样工作。

回答by Brian Hsu

Yes, it is totally possible and in fact very easy. The following code will work as expected.

是的,这是完全可能的,实际上非常容易。以下代码将按预期工作。

// TestArray.scala
object TestArray {
    def test (array: Array[Int]) = array.foreach (println _)
}

-

——

// Sample.java
public class Sample
{
    public static void main (String [] args) {
        int [] x = {1, 2, 3, 4, 5, 6, 7};
        TestArray.test (x);
    }
}

Use the following command to compile/run.

使用以下命令编译/运行。

$scalac TestArray.scala
$javac -cp .:/opt/scala-2.8.0/lib/scala-library.jar Sample.java
$java -cp .:/opt/scala-2.8.0/lib/scala-library.jar Sample