英文:
How to access scala object inside scala class in java?
问题
我有一个类似这样的 Scala 类:
class A {
object B {
def c(d: Int) = d + 4
}
}
我如何从 Java 代码中访问函数 c
?
编辑:假设我无法以任何方式更改 Scala 类。
编辑#2:
以下是示例:
public class Q {
public void qwe() {
A a = new A();
a.B().c(4); // 无法解析方法 'B' 在 'A' 中
}
}
英文:
I have scala class like:
class A {
object B {
def c(d: Int) = d + 4
}
}
How do i access function c
from a java code?
Edit: assume that I can't change scala class anyhow.
Edit#2:
Here is example of
public class Q {
public void qwe() {
A a = new A();
a.B().c(4); //Cannot resolve method 'B' in 'A'
}
}
答案1
得分: 4
object B`从类中转换为公共方法`B()`,您可以按以下方式访问该方法:
```java
A a = new A();
System.out.println(a.B().c(4));
底层实现
A.scala
class A {
object B {
def c(d: Int) = d + 4
}
}
将上述类编译为Java后,如下所示
scalac A.scala
javap -p A.class
public class A {
private volatile A$B$ B$module;
public A$B$ B();
private final void B$lzycompute$1();
public A();
}
英文:
object B
from class gets converted to public method B()
which you can access as follows:
A a = new A();
System.out.println(a.B().c(4));
Under The Hood
A.scala
class A {
object B {
def c(d: Int) = d + 4
}
}
Above class when compiled to java looks like below
scalac A.scala
javap -p A.class
public class A {
private volatile A$B$ B$module;
public A$B$ B();
private final void B$lzycompute$1();
public A();
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论