8

I have a library here with some Java classes. One class has some protected static methods, which I realize is sorta an OOP no-no but I can't change its code. Assuming I have a Scala class that subclasses the aforementioned Java class, how can I call its protected static members?

3
  • 3
    Is it not an option to make a Java subclass that calls the super class method? You could then make your Java class accessible to Scala. Commented Dec 15, 2010 at 0:55
  • Ah, yes, I guess I could go that route. Thanks. Seems a bit odd that it's not possible directly though! Commented Dec 15, 2010 at 0:57
  • Maybe it's possible more directly in Scala, I don't know. That's why I posted this as a comment and not as an answer. Obviously, a "super" call cannot work because Scala has no static inheritance. Maybe you can make a Scala object that extends the class in question and then call "LibraryClassName.staticMethodName(...)", thereby avoiding to use "super"? I'm not sure if this would work. Commented Dec 15, 2010 at 1:10

1 Answer 1

21

See Frequently Asked Questions - Java Interoperability:

This is a known limitation of Scala: there is no notion of 'static' members in Scala. Instead, Scala treats static members of class Y as members of the singleton object Y (the companion object of class Y). When inheriting from this class, one can access only protected members of class Y but cannot access protected members of object Y.

There's no way Scala can simulate static protected without impairing the integrity of Scala's object model in a fundamental way, so this is not going to change. To work around this limitation, one has to create an implementation of the enclosing class with Java code which encapsulates all accesses to the protected static inner class.

See ticket #1806 for more information and a concrete example of the limitation and its workaround.

Sign up to request clarification or add additional context in comments.

3 Comments

The "frequently" asked questions are so rarely asked that few people notice its existence. :-)
JFYI, this is fixed in 2.10.0-M2
@OlegYch: add that as an answer?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.