Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala access inherited static member of Java class

Tags:

java

scala

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.

like image 258
Nyavro Avatar asked Dec 28 '25 23:12

Nyavro


1 Answers

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, e.g. (assuming you can change B):

public class B implements A {
    public static final String LOWER = "lower";
    public static final String HIGHER1 = HIGHER;
}
like image 77
Alexey Romanov Avatar answered Dec 30 '25 11:12

Alexey Romanov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!