How can I pass a Scala object reference around in Java?

后端 未结 2 1824
刺人心
刺人心 2020-12-11 02:29

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 Loca         


        
相关标签:
2条回答
  • 2020-12-11 03:00

    While the $.MODULE$ method works, a slightly less jarring way to get Java-interop with Scala objects is to expose the object as a method on itself.

    The Scala:

    object LocalEnvironment extends Environment{
       def instance = this
    }
    

    The Java:

    Environment getEnvironment() { return LocalEnvironment.instance(); }  
    

    This works because under the covers, .instance() is implemented as a static method on class LocalEnvironment. There has been some discussion about Scala objects getting an "instance" method by default, for just this purpose.

    0 讨论(0)
  • 2020-12-11 03:14
    { return LocalEnvironment$.MODULE$; }
    

    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 called MODULE$ that is populated with the single valid instance of that class. But there is also a class called ObjectName that copies all the methods as static methods. That way you can use it like Java (just call ObjectName.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 object is designed to emulate in Java--you then have to know how Scala represents it internally.

    0 讨论(0)
提交回复
热议问题