[英]Why can't I assign an Scala Object to a Java variable?
I have this monolithic Java-Application that I want to port to newer techniques and I want to apply Scala wherever it makes sense. 我有这个整体的Java应用程序,我想移植到较新的技术,并且我想在任何有意义的地方应用Scala。
Now I translated a rather huge java-singleton class implementation to a Scala object. 现在,我将一个相当庞大的java-singleton类实现转换为Scala对象。
In another class I used to do this (JAVA): 在另一个类中,我曾经这样做(JAVA):
public class MyOtherClass
{
protected MyClass myClass;
public MyOtherClass()
{
myClass = MyClass.getInstance();
}
}
Now I'd like to do the following: 现在,我要执行以下操作:
public class MyOtherClass
{
protected MySCALAClass myClass;
public MyOtherClass()
{
myClass = MySCALAClass$.MODULE$;
}
}
But this doesn't work. 但这是行不通的。 It says:
它说:
Required MyScalaClass, Found MyScalaClass$
必需的MyScalaClass,找到的MyScalaClass $
I also tried to create a small function 我也尝试创建一个小功能
def getInstance() = this
but of course this yields the same problem. 但这当然会产生相同的问题。
Any ideas? 有任何想法吗? I have searched this topic and I see how it is not a problem if you just want to call the methods of the object, but I would need to rewrite many, many calls to the "myClass"-object to even test this.
我已经搜索了这个主题,并且看到如果您只想调用对象的方法,这不是问题,但是我将需要重写许多对“ myClass”对象的调用,甚至进行测试。
edit : I'm fully aware that I could rename every call to "myClass" to "MySCALAClass", but that is no real fix, just a workaround and it is tedious for a big project. 编辑 :我完全知道,我可以将对“ myClass”的每个调用重命名为“ MySCALAClass”,但这并不是真正的解决方案,只是一种解决方法,对于一个大型项目而言是乏味的。
I think @neuronaut 's comment is correct. 我认为@neuronaut的评论是正确的。
See following questions: 请参阅以下问题:
The singleton class ( MySCALAClass$
in your case) is not a subclass of the original class ( MySCALAClass
) and so the singleton object ( MySCALAClass$.MODULE$
) is not an instance of it either. 单例类(在您的情况下为
MySCALAClass$
)不是原始类( MySCALAClass
)的子类,因此单例对象( MySCALAClass$.MODULE$
)也不是其实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.