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

后端 未结 2 1827
刺人心
刺人心 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.

提交回复
热议问题