I want to return from a Java method a reference to a Scala object. How can I do that?
My Scala objects are like this:
trait Environment
object LocalEnvironment extends Environment {...}
object ServerEnvironment extends Environment {...}
… and I want my Java method to be like this:
Environment getEnvironment() { return LocalEnvironment; } // DOES NOT COMPILE
Is there a way to do this?
should work.
Edit: the reason why this works is that this is how Scala represents singleton objects. The class
ObjectName$has a field in it calledMODULE$that is populated with the single valid instance of that class. But there is also a class calledObjectNamethat copies all the methods as static methods. That way you can use it like Java (just callObjectName.methodName) in most cases, and Scala gets to have a real class to pass around.But when Java needs to pass the class around–not something normally done with a bunch of static methods, which is what
objectis designed to emulate in Java–you then have to know how Scala represents it internally.