Import Scala object within object in Java

325 views Asked by At

I have an object within another object in Scala which I want to import in Java. The setup is something like this:

Scala:

package scalapart;

object Outer {
    object Inner {
        def method: String = "test"
    }
}

Java:

import scalapart.Outer.Inner;
...
Outer.Inner.method()

Unfortunately, I get cannot find symbol in line 1 of the Java code. And if I import scalapart.Outer;, then the second line reports the same issue.

Is there a way to import a Scala object that is defined inside another Scala object in Java?

1

There are 1 answers

4
Alin Gabriel Arhip On

You can either used it directly:

    // assuming they are in the same package:
    String mystr = Outer.Inner$.MODULE$.method();
    System.out.println(mystr);  // test

    // if in other package just:
    import packageName.Outer;

    String mystr = Outer.Inner$.MODULE$.method();

Or do a static import and use it like this (or similar):

import static packageName.Outer.Inner$.MODULE$;

String mystr = MODULE$.method();

Java doesn’t have any direct equivalent to the singleton object, so for every Scala singleton object, the compiler creates a synthetic Java class with the same name plus a dollar sign appended at the end) for that object and a static field named MODULE$ to hold the single instance of the class. So, to ensure there is only one instance of an object, Scala uses a static class holder.

Your disassembled code looks something like this:

public final class Outer
{
    public static class Inner$
    {
        public static final Inner$ MODULE$;

        static {
            MODULE$ = new Inner$();
        }

        public String method() {
            return "test";
        }
    }
}

public final class Outer$ {
    public static final Outer$ MODULE$;

    static {
        MODULE$ = new Outer$();
    }

    private Outer$() {
    }
}