0

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

2

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

4 Comments

What would be the import statement in the first example?
Sorry I forgot to add it: import it with using it's packageName: import mypackage.Outer; should work. Intellij will figure it out. Updated the answer to include this.
Unfortunately this doesn't work for me. I will try to recreate this MWE and report back.
What Scala version are you using? I tested this with Scala 2.13.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.