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

标签 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[],但这并没有解决问题。一定存在某种转换?

最佳答案

正如其他人指出的那样,转换没有问题。我的 IDE 行为错误,并显示编译没有问题的假想错误。此时调用main-method中的receive方法在如下代码中被标记为错误:

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]);
    }
}

斯卡拉:

package stackOverflow

import stackOverflow._

class ScalaByteReceiver{

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

因此 Java 和 Scala 可以很好地相互理解。

关于java - 如何将 Java 字节数组转换为 Scala 字节数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6237666/

相关文章:

java - 制作系统应用时无法加载.so库文件

java - 测试代码和主代码的独立类路径

scala - 新的 dotty 运行时对我来说完全消失了

Java:内存高效的 ByteArrayOutputStream

Java:随机访问文件模式 "rws"与 "rwd"?

Windows上的java println输出编码

scala - 如何初始化元组列表并在scala中添加项目

scala - SBT:对所有项目运行一个操作

Java - 将字节数组或字符串转换为(虚拟)文件

c# - 将字节数组复制到剪贴板