如何在Java中访问Scala类内部的Scala对象?

huangapple go评论77阅读模式
英文:

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();
}

huangapple
  • 本文由 发表于 2020年10月12日 23:09:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/64320451.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定