Passing Java array to Scala
Solution 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.
Solution 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
halfwarp
Updated on June 04, 2022Comments
-
halfwarp almost 2 years
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?
-
halfwarp over 13 yearsThanks. It was Eclipse's plugin fault.
-
MarnixKlooster ReinstateMonica about 13 yearsFrom 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)
, whereargs
is of typeString[]
, andApp
is a Scalaobject
with adef 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.