将 Java 数组传递给 Scala
尽管我已经使用 Scala 一段时间,并且之前也将其与 Java 混合使用,但我还是遇到了一个问题。
如何将 Java 数组传递给 Scala?我知道相反的方法相当简单。然而从 Java 到 Scala 却并非如此。
我应该在 Scala 中声明我的方法吗?
这是我想要实现的一个小例子:
Scala:
def sumArray(ar: Array[Int]) = ...
Java:
RandomScalaClassName.sumArray(new int[]{1,2,3});
Is this possible?
Although I've been using Scala for a while and have mixed it with Java before, I bumped on a problem.
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.
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});
Is this possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
绝对地!
Scala 中的
Array[T]
类直接映射到 Java 类型T[]
。它们在字节码中具有完全相同的表示形式。至少在2.8中是这样的。 2.7 中的情况略有不同,涉及大量数组装箱,但理想情况下您现在应该在 2.8 上工作。
所以是的,它会完全按照你写的那样工作。
absolutely!
The
Array[T]
class in Scala is mapped directly to the Java typeT[]
. They both have exactly the same representation in bytecode.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.
是的,这是完全可能的,而且事实上非常容易。以下代码将按预期工作。
-
使用以下命令编译/运行。
Yes, it is totally possible and in fact very easy. The following code will work as expected.
-
Use the following command to compile/run.