如何将Java字节数组转换为Scala字节数组? [英] How do I convert a Java byte array into a Scala byte array?

查看:229
本文介绍了如何将Java字节数组转换为Scala字节数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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[].

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

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

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

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

IDE告诉我它不可能:

The IDE tells me its not possible:

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

作为附加约束,不优选更改Scala方法。在Java方面,我尝试使用 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?

推荐答案

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

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

所以Java和Scala很了解彼此。

So Java and Scala understand each other nicely.

这篇关于如何将Java字节数组转换为Scala字节数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆