Passing Java array to Scala
Asked Answered
C

2

8

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?

Cutlery answered 15/10, 2010 at 8:40 Comment(0)
C
18

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.

Concinnity answered 15/10, 2010 at 10:43 Comment(0)
A
8

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
Allure answered 15/10, 2010 at 8:57 Comment(2)
Thanks. It was Eclipse's plugin fault.Cutlery
From this comment I understand that you had the same problem I see right now. In a Java class I have a call App.main(args), where args is of type String[], and App is a Scala object with a def main(args: Array[String]). Now the Eclipse JDT source analyzer marks that call as an error: "The method main(Array) in the type App is not applicable for the arguments (String[])". This is harmless, and the error doesn't even show up in the Problems view. I don't know whether this is a problem in the JDT, in the Scala plug-in, in the Scala compiler, or in multiple of the above.Phillipp

© 2022 - 2024 — McMap. All rights reserved.