6

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?

1 Answer 1

4
object ClassFromScala extends ClassFromJava {
  def VERSION = ClassFromJava.VERSION
}
Sign up to request clarification or add additional context in comments.

3 Comments

So I need explicit declare all field that I want to use, and could not have them automatically. It this right?
why is ClassFromJava.VERSION not visible?
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.