Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a protected static Java method from Scala

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?

like image 688
J Cooper Avatar asked Dec 15 '10 00:12

J Cooper


People also ask

What are “static” methods in Scala?

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:

What is the best way to call a method in Scala?

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.

How to access a protected method of a class in Java?

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.*;

How to use the Java optional class in Scala?

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:


1 Answers

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.

like image 84
Vasil Remeniuk Avatar answered Sep 18 '22 13:09

Vasil Remeniuk