javascalascala-java-interop

How to access scala object inside scala class in java?


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'
    }
}

Solution

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