1

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 Answer 1

4

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();
}
Sign up to request clarification or add additional context in comments.

2 Comments

This doesn't work in idea. And Gradle also throw error when i try to compile it. here is example of java class ``` public class Q { public void qwe() { A a = new A(); a.B().d(4); } } ```
Idea does not understand, maybe bug with intellij. You can still run and should print 8

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.