Consider the following classes:
//A.java:
public interface A {
public static final String HIGHER = "higher";
}
//B.java:
public class B implements A {
public static final String LOWER = "lower";
}
In java code I have access to both HIGHER and LOWER fields:
//JavaClient.java:
public class JavaClient {
public static void main(String[] args) {
System.out.println(B.HIGHER);
System.out.println(B.LOWER);
}
}
But I cannot do the same thing in Scala!
//ScalaClient.scala:
object ScalaClient {
def main (args: Array[String]) {
println(B.HIGHER) // Compilation error
println(B.LOWER) // OK
}
}
This is very unexpected for me. Why Scala cannot see inherited psf field? How to workaround?
Note : In my real code I don't have access to interface A, since it is protected and nested in another class.
Just access HIGHER
as A.HIGHER
. So far as Scala is concerned, static
members in Java are members of companion objects, and the companion object of B
doesn't extend the companion object of A
: that's why you can't use B.HIGHER
.
Note: In my real code I don't have access to interface A, since it is protected and nested in another class.
In this case, however, you have a problem. The one thing I can think of is to expose the constant explicitly from Java code, eg (assuming you can change B
):
public class B implements A {
public static final String LOWER = "lower";
public static final String HIGHER1 = HIGHER;
}
You can fix the problem in two ways.
1) Just remove the static
word in interface A & interface B and it should work.
Or
2) Create a trait ( trait is a feature in Scala, which closely resembles java interface but there are many differences )
trait A { }
object A {
final val Higher = "higher"
}
Now you can access A.Higher
from your caller Scala class.
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.