access java base class's static member in scala

前端 未结 1 1547
旧时难觅i
旧时难觅i 2021-01-12 17:17

Ihave some codes written in Java. And for new classes I plan to write in Scala. I have a problem regarding accessing the protected static member of the base class. Here is t

相关标签:
1条回答
  • 2021-01-12 17:50

    This isn't possible in Scala. Since Scala has no notation of static you can't access protected static members of a parent class. This is a known limitation.

    The work-around is to do something like this:

    // Java
    public class BaseStatic extends Base {
      protected int getCount() { return Base.count; }
      protected void setCount(int c) { Base.count = c; }
    }
    

    Now you can inherit from this new class instead and access the static member through the getter/setter methods:

    // Scala
    class Derived extends BaseStatic {
      println(getCount());
    }
    

    It's ugly—but if you really want to use protected static members then that's what you'll have to do.

    0 讨论(0)
提交回复
热议问题