如何将Java字节数组转换为Scala字节数组?

时间:2011-06-04 15:37:01

标签: java scala bytearray

我是Scala的新手,目前正在参与涉及Java和Scala模块的项目。现在我想使用byte []类型的参数从Java调用Scala方法。

Scala方法具有签名:def foo(data: Array[Byte])

Java调用如下所示:foo(x),其中x的类型为byte[]

IDE告诉我它不可能:

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

作为附加约束,不优选更改Scala方法。在Java方面,我尝试使用Byte[],但这并没有解决问题。必须存在一些转换吗?

2 个答案:

答案 0 :(得分:4)

正如其他人指出的那样,转换没有问题。我的IDE表现错误,并显示虚构的错误,编译没有问题。此时,以下代码中main方法中receive方法的调用标记为错误:

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

但是,这段代码解释了我的问题,编译得很好并产生了预期的结果:

爪哇:

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
  }
}

所以Java和Scala很好地相互理解。

答案 1 :(得分:1)

我尝试重现您的错误,但它按预期运行。 使用scala 2.9.0和sbt

运行

java代码:

package stackOverflow;

public class ByteContainer {

    private byte[] bytes;

    public ByteContainer(byte[] bytes){
        this.bytes = bytes;
    }

    public byte[] getBytes() {
        return bytes;
    }

    public void setBytes(byte[] bytes) {
        this.bytes = bytes;
    }

}

scala代码:

package stackOverflow

import stackOverflow._

class ScalaByte{
    val bytes:Array[Byte] = "this is my test".getBytes()
}

object ByteUser extends App{
    val b = new ByteContainer((new ScalaByte()).bytes)
    val s = b.getBytes()
    println(s)
}

输出:[B @ 6ef38f6f

编译并运行。这不是你问的问题吗?随时发表评论。