tags:

views:

71

answers:

1

Hello,

I'm would like to know how could I inherent static field from Java class in Scala.

Here is a Java example, if I a class named ClassFromJava, I could extend it, add some static field, and use the subclass to access the VERSION field.

public class ClassFromJava {
    public static int VERSION = 1;
}

public class ClassFromJavaSub extends ClassFromJava {
    public static String NOTE = "A note";
}

public class Test {
    public static void main (String [] args) {
       System.out.println (ClassFromJavaSub.VERSION); // This works.
    }
}

But if I want extends ClassFromJava in Scala, and add some constant value, it seems not work.

object ClassFromScala extends ClassFromJava {
    val NOTE = "A Note"
}

object Test {
    def main (args: Array[String]) {
        // This line won't compile
        // ClassFromScala has no value VERSION.
        println (ClassFromScala.VERSION) 
    }
}

What should I do if I would like ClassFromScala also has the VERSION variable?

+2  A: 
object ClassFromScala extends ClassFromJava {
  def VERSION = ClassFromJava.VERSION
}
Rex Kerr
So I need explicit declare all field that I want to use, and could not have them automatically. It this right?
Brian Hsu
@Rex why is ClassFromJava.VERSION not visible?
huynhjl
@Brian - You need to declare them _if_ you want to use them as `ClassFromScala.INHERITED_CONSTANT`. @huynhjl - `ClassFromJava.VERSION` is visible, but Brian said that he wanted `ClassFromScala` to appear to have the constant also.
Rex Kerr