How to convert a Scala Array[Byte] to Java byte[]?

11,549

Scala's Array[Byte] is already a Java's byte[]. Proof:

object ScalaSide extends Application {
  val a = Array[Byte](1, 2, 3)

  JavaSide.doSmth(a)
}

--

import java.util.Arrays;

public class JavaSide {
    public static void doSmth(Object arr) {
        byte[] b = (byte[]) arr;
        System.out.println(Arrays.toString(b));
    }
} 

Result:

[1, 2, 3]
Share:
11,549
SkyWalker
Author by

SkyWalker

How would you be rated on a technical skill that you haven't used yet e.g. tableau? Check out my Stack Overflow skill recommender system: https://github.com/bravegag/HarvardX-Skillability

Updated on June 05, 2022

Comments

  • SkyWalker
    SkyWalker about 2 years

    I have an Akka application with actors written in Scala and others in Java. In one case a Scala Actor writes an Array[Byte] and I need to deserialize this from a Java Actor. In this use-case I ultimately need a String representation in Java of the Array[Byte] so that would also solve my problem.

    Scala Actor:

    val outputStream = new java.io.ByteArrayOutputStream()
    val bufferedOutputStream = new java.io.BufferedOutputStream(outputStream, 1024)
    val exitCode : Integer = processBuilder #> bufferedOutputStream !
    bufferedOutputStream.flush
    val content = outputStream.toByteArray // this gives an Array[Byte]
    javaActorRef.tell(content, getSelf())
    

    Java Actor:

    /**
     * {@inheritDoc}
     */
    @Override
    public void onReceive(Object object) throws Exception {
        // object has a Scala Array[Byte] how do I convert here to 
        // byte[] or to String?
    
  • mttdbrd
    mttdbrd over 10 years
    That's what I thought.
  • Bill Woodger
    Bill Woodger about 9 years
    If you have a problem, which you seem to have from your final two lines, you should ask it as a new question, not post it as an answer. You can include a link to this question if you feel it helps explain your question (use the share link under the question).
  • dividebyzero
    dividebyzero about 8 years
    It seems you actually need something like Array[Byte](1.toByte, ...) etc because Array[Byte] won't take an Int literal.
  • mdornfe1
    mdornfe1 over 3 years
    But what if the method is void doSmth(byte[] arr) ? What would do to a before passing it to the method?