Passing Java array to Scala

懵懂的女人 提交于 2019-11-30 04:20:14

问题


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?


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/3940699/passing-java-array-to-scala

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!