简体   繁体   English

如何在Java中传递Scala对象引用?

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

I want to return from a Java method a reference to a Scala object. 我想从Java方法返回对Scala对象的引用。 How can I do that? 我怎样才能做到这一点?

My Scala objects are like this: 我的Scala对象是这样的:

trait Environment 

object LocalEnvironment extends Environment {...}
object ServerEnvironment extends Environment {...}

... and I want my Java method to be like this: ...我希望我的Java方法是这样的:

Environment getEnvironment() { return LocalEnvironment; }  // DOES NOT COMPILE

Is there a way to do this? 有没有办法做到这一点?

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. 虽然$ .MODULE $方法有效,但是使用Scala对象获得Java-interop的一种稍微不那么刺耳的方法是将对象作为一种方法暴露给自己。

The Scala: 斯卡拉:

object LocalEnvironment extends Environment{
   def instance = this
}

The Java: Java:

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

This works because under the covers, .instance() is implemented as a static method on class LocalEnvironment. 这是有效的,因为在底层,.instance()是作为LocalEnvironment类的静态方法实现的。 There has been some discussion about Scala objects getting an "instance" method by default, for just this purpose. 出于此目的,已经有一些关于Scala对象默认获得“实例”方法的讨论。

{ return LocalEnvironment$.MODULE$; }

should work. 应该管用。


Edit: the reason why this works is that this is how Scala represents singleton objects. 编辑:这就是为什么Scala代表单例对象的原因。 The class ObjectName$ has a field in it called MODULE$ that is populated with the single valid instance of that class. ObjectName$类中有一个名为MODULE$的字段,该字段填充了该类的单个有效实例。 But there is also a class called ObjectName that copies all the methods as static methods. 但是还有一个名为ObjectName的类将所有方法复制为静态方法。 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. 这样你就可以像Java一样使用它(在大多数情况下只调用ObjectName.methodName ),而Scala可以有一个真正的类来传递。

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. 但是当Java需要传递类时 - 不是通常使用一堆静态方法完成的事情,这是设计用Java模拟的object - 然后你必须知道Scala如何在内部表示它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM