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?
If you’re coming to Scala from a language other than Java, “static” methods in Java are methods that can be called directly on a class, without requiring an instance of the class. For instance, here’s an example of a method named increment in a Scala object named StringUtils:
When calling Java with Scala, Java static method calls are generally the best place to start when looking at cross-language functionality because they require no object to be created. The JMSL library has numerous static methods, most with a method signature that requires passing one or more values.
The method display in class A is protected and class B is inherited from class A and this protected method is then accessed by creating an object of class B. import p1.*;
When you need to use the Java Optional class in your Scala code, import the scala.jdk.OptionConverters object, and then use the toScala method to convert the Optional value to a Scala Option. To demonstrate this, here’s a Java class with two Optional<String> values, one containing a string and the other one empty:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With