4

I cannot reference Scala classes from Java code when using Eclipse IDE. The Scala class in question is nested within a Scala-object structure. When trying to use the class in Java code, Eclipse complains about using the binary name.

Below is an example of Scala code defining the class of interest (Inner):

package mypackage;

object Outer {
  object Middle {
    class Inner {
      def msg() {
        println("Running");
      }
    }
  }
}

To use the class Inner in Java code, I use the following code:

mypackage.Outer$Middle$Inner inner = new mypackage.Outer$Middle$Inner();
inner.msg();

However, Eclipse (Indigo) compiler complains with the following message at the first line:

The nested type mypackage.Outer$Middle$Inner cannot be referenced using its binary name

Interestingly, the Java code above works when used with NetBeans 6.9.1.

Is this an issue with Eclipse compiler? Are there any flags to allow using binary names? Or, alternatively, is this an issue with Scala or the way I am using it?

1 Answer 1

1

Deeply nested objects cannot be accessed from Java. Neither from Eclipse, command line or any build tool. The bytecode translation loses the nesting information.

Eclipse does not allow you to use $ names, so it will complain. If you care about Java interop, you should stick to Java-like Scala at the boundaries. Top-level classes, pure-traits or abstract classes, no higher-order methods, etc.

Sign up to request clarification or add additional context in comments.

4 Comments

So is the fact that Netbeans succeeds in running the code just a lucky exception on their side?
I'd be pretty surprised if it does. What is the syntax that works in Netbeans?
Exactly the syntax as described in the question. I build a Scala jar and use it in NetBeans Java project. I have added an executable example to GitHub: github.com/andriusvelykis/scala-nested-class-netbeans
@IulianDragos It wouldn't be the first time that I've seen NetBeans accepting something that Eclipse doesn't. Eclipse uses its own incremental compiler, hence why it can run with only a JRE and not a JDK installed. NetBeans, on the other hand, expects a JDK to be available and uses the compiler provided there. Correct me if I'm wrong on this one. Anyway, the Eclipse compiler may behave differently from the regular javac. And that could be either by mistake, or by adhering more strictly to the spec. Chances are that if you build with Ant or Maven using a separate JDK, it'll work.

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.