简体   繁体   中英

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.

Now I translated a rather huge java-singleton class implementation to a Scala object.

In another class I used to do this (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$

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.

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.

I think @neuronaut 's comment is correct.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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