从 Java 调用带有参数和内部类的 scala 抽象类
如果我定义一个 Scala 类:
class X(i:Int) {
println (i)
}
如何在 Java 代码中使用该类?
[编辑]实际上,我的问题稍微复杂一些,
我有一个抽象类,
abstract class X(i:Int) {
println (i)
def hello(s:String):Unit
}
我需要在Java代码中使用它。可以轻松做到吗?
[EDIT2] 考虑以下代码
object B {
case class C(i:Int)
}
abstract class X(i:Int) {
println (i)
def hello(a:B.C):Unit
}
在这种情况下,以下 java 代码在 Netbeans IDE 中给出错误,但构建正常:
public class Y extends X {
public void hello(B.C c) {
System.out.println("here");
}
public Y(int i) {
super(i);
}
}
我得到的错误是:
hello(B.C) in Y cannot override hello(B.C) in X; overridden method is static, final
Netbeans 6.8,Scala 2.8。
到目前为止,我认为唯一的解决方案是忽略 NB 错误。
这是一张显示我得到的确切错误的图像:
If I define a Scala class:
class X(i:Int) {
println (i)
}
How do I use this class in Java code?
[EDIT] Actually, my problem is slightly more complicated
I have an abstract class
abstract class X(i:Int) {
println (i)
def hello(s:String):Unit
}
I need to use this in Java code. Is it possible to do it easily?
[EDIT2] Consider the following code
object B {
case class C(i:Int)
}
abstract class X(i:Int) {
println (i)
def hello(a:B.C):Unit
}
In this case, the following java code gives an error in Netbeans IDE but builds fine:
public class Y extends X {
public void hello(B.C c) {
System.out.println("here");
}
public Y(int i) {
super(i);
}
}
The error I get is:
hello(B.C) in Y cannot override hello(B.C) in X; overridden method is static, final
Netbeans 6.8, Scala 2.8.
As of now I think the only solution is to ignore the NB errors.
Here is an image showing the exact error(s) I get:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为您的类生成的字节码将与 Java 定义相同:
完全按照使用等效 Java 的方式使用它;子类并提供
hello
方法的具体实现。The generated bytecode for your class will be identical to the Java definition:
Use it exactly as you would for this equivalent Java; subclass and provide a concrete implementation of the
hello
method.您需要在类路径中传递 Scala 库 jar 来编译扩展 Scala 类的任何 Java 代码。例如:
You need to pass the Scala library jar in the class path to compile any Java code extending a Scala class. For example:
您应该能够从 Java 调用 Scala 代码(可能需要进行一些名称修改等)。如果您尝试以下操作会发生什么?
在更复杂的情况下,您可以使用 javap 或类似工具来了解 Scala 代码是如何翻译的。如果没有其他办法,您仍然可以在 Scala 端编写一些辅助方法,以便更轻松地从 Java 端进行访问(例如,当涉及隐式时)。
You should be able to call Scala code from Java (maybe with some name mangling and so on). What happens if you try the following?
In more complicated cases you can use
javap
or similar tools to find out how the Scala code got translated. If nothing else works, you can still write some helper methods on Scala side to make access from Java side easier (e.g. when implicits are involved).