将Java数组传递给Scala [英] Passing Java array to Scala
问题描述
虽然我已经使用Scala一段时间并且之前已经将它与Java混合,但我遇到了一个问题。
Although I've been using Scala for a while and have mixed it with Java before, I bumped on a problem.
如何将Java数组传递给Scala呢?我知道反过来相当简单。但Scala的Java并不是这样。
How can I pass a Java array to Scala? I know that the other way around is fairly straightforward. Java to Scala is not so however.
我应该在Scala中声明我的方法吗?
Should I declare my method in Scala?
以下是我想要实现的一个小例子:
Here is a small example of what I'm trying to achieve:
Scala:
def sumArray(ar: Array[Int]) = ...
Java:
RandomScalaClassName.sumArray(new int[]{1,2,3});
这可能吗?
推荐答案
绝对!
Scala中的 Array [T]
类已映射直接到Java类型 T []
。它们在字节码中具有完全相同的表示。
The Array[T]
class in Scala is mapped directly to the Java type T[]
. They both have exactly the same representation in bytecode.
至少,这是2.8中的情况。 2.7中的情况略有不同,涉及大量的数组拳击,但理想情况下你现在应该在2.8上工作。
At least, this is the case in 2.8. Things were a little different in 2.7, with lots of array boxing involved, but ideally you should be working on 2.8 nowadays.
所以是的,它会像你一样工作写完了。
So yes, it'll work exactly as you've written it.
这篇关于将Java数组传递给Scala的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!