Using the Scala class defined in a package object from Java

The following Scala example defines a class inside a package object:

package com.mycompany package object test { class MyTest { def foo(): Int = { 42 } } } 

The following three classes are generated:

 com/mycompany/test/package.class com/mycompany/test/package$.class com/mycompany/test/package$MyTest.class 

The problem occurs when trying to use the MyTest class from Java. I think that since package$MyTest contains $ in the name, Java does not recognize its existence. However, the package$ class is available.

Running javap on package$MyTest.class returns:

 Compiled from "Test.scala" public class com.mycompany.test.package$MyTest { public int foo(); public com.mycompany.test.package$MyTest(); } 

I tried accessing the class using Eclipse, Intellij and Netbeans, without success. Can I use Scala classes defined in package objects from Java?

+6
source share
2 answers

Class definition inside package object test is not currently implemented in the same way as defining it inside a package test , although it probably should (this is tracked as SI-4344 ).

Because of this, as a rule, it is good practice to place only definitions in package objects that cannot be top-level, for example, vals, defs, etc. (after all, this is the goal of the package objects) and leave the class / object definitions in the standard package definition:

 package com.mycompany package object test { // vals, defs, vars, etc. val foobar = 42 } package test { // classes, objects, traits, etc. class MyTest { def foo(): Int = { 42 } } } 

This will result in a normal MyTest class, easily accessible from Java:

 com/mycompany/test/MyTest.class com/mycompany/test/package.class com/mycompany/test/package$.class 
+5
source

package$MyTest follows the JVM convention for nested classes, so it will appear as package.MyTest ... except that it is not a legal name in Java. This means that it cannot be accessed.

+3
source

All Articles