将 Java 数组传递给 Scala

发布于 2024-09-27 10:25:22 字数 369 浏览 0 评论 0原文

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

如何将 Java 数组传递给 Scala?我知道相反的方法相当简单。然而从 Java 到 Scala 却并非如此。

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

这是我想要实现的一个小例子:

Scala:

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

Java:

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

Is this possible?

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

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.

Should I declare my method in 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

山色无中 2024-10-04 10:25:23

绝对地!

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

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

所以是的,它会完全按照你写的那样工作。

absolutely!

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

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.

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

黒涩兲箜 2024-10-04 10:25:23

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

// 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);
    }
}

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

$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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文