Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a Java byte array into a Scala byte array?

I am new to Scala and work currently on a project involving both Java and a Scala modules. Now I'd like to call a Scala method from Java using a parameter of type byte[].

The Scala method has the signature: def foo(data: Array[Byte])

The Java call looks like this: foo(x), where x has the type byte[].

The IDE tells me its not possible:

The method foo(Array) in the type Bar is not applicable for the arguments (byte[])

As an additional constraint it is not preferred to change the Scala method. On the Java side I tried using Byte[], but this didn't solve the problem. There must exist some conversion?

like image 709
mtsz Avatar asked Jun 04 '11 15:06

mtsz


1 Answers

As others pointed out, there is no problem in conversion. My IDE is behaving erroneous, and showing imaginary errors which compile without problems. At this moment the call of the receive Method in the main-method in following code is marked with the error:

The method receive(Array) from the type ScalaByteReceiver refers to the missing type Array

But this code, which exemplifies my question, compiles fine and yields the expected result:

Java:

package stackOverflow;

public class JavaByteSender {    
    public static void main(String... args) {
    new ScalaByteReceiver().receive(new byte[4]);
    }
}

Scala:

package stackOverflow

import stackOverflow._

class ScalaByteReceiver{

  def receive(bytes: Array[Byte]) {    
    println(bytes.length);
    // prints 4
  }
}

So Java and Scala understand each other nicely.

like image 183
mtsz Avatar answered Sep 21 '22 22:09

mtsz