Brian Hsu
Brian Hsu

Reputation: 8821

Scala object extends Java class static field

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?

Upvotes: 6

Views: 1789

Answers (1)

Rex Kerr
Rex Kerr

Reputation: 167891

object ClassFromScala extends ClassFromJava {
  def VERSION = ClassFromJava.VERSION
}

Upvotes: 4

Related Questions