Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Java array to Scala

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?

like image 386
halfwarp Avatar asked Oct 15 '10 08:10

halfwarp


People also ask

How do you create an array of objects in Scala?

Creating an Array and Accessing Its ElementsScala translates the first line in the example above into a call to Array::apply(), defined in the Array companion object. Such a method takes a variable number of values as input and creates an instance of Array[T], where T is the type of the elements.

What is array in Scala?

Array is a special kind of collection in scala. it is a fixed size data structure that stores elements of the same data type. The index of the first element of an array is zero and the last element is the total number of elements minus one. It is a collection of mutable values.


1 Answers

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.

like image 197
Kevin Wright Avatar answered Nov 16 '22 01:11

Kevin Wright