如何在Java中传递Scala对象引用? [英] How can I pass a Scala object reference around in Java?

查看:173
本文介绍了如何在Java中传递Scala对象引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从Java方法返回对Scala对象的引用。我该怎么做?

I want to return from a Java method a reference to a Scala object. How can I do that?

我的Scala对象是这样的:

My Scala objects are like this:

trait Environment 

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

...我希望我的Java方法是这样的:

... and I want my Java method to be like this:

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

有没有办法做到这一点?

Is there a way to do this?

推荐答案

{ return LocalEnvironment$.MODULE$; }

应该有效。

编辑:这就是为什么这就是Scala代表单例对象的原因。类 ObjectName $ 中有一个名为 MODULE $ 的字段,该字段填充了该类的单个有效实例。但是还有一个名为 ObjectName 的类,它将所有方法复制为静态方法。这样你就可以在大多数情况下像Java一样使用它(只需调用 ObjectName.methodName ),并且Scala可以传递一个真正的类。

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.

但是当Java需要传递类时 - 不是通常用一堆静态方法完成的,这就是 object 的设计用Java模拟 - 然后你必须知道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中传递Scala对象引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆