Access to static member of java base class in scala

I have codes written in Java. And for new classes I plan to write in Scala. I have a problem accessing a protected static member of a base class. Here is a sample code:

Java Code:

class Base{ protected static int count = 20; } 

scala code:

 class Derived extends Base{ println(count); } 

Any suggestion on this? How can I solve this problem without changing the existing base class

+6
source share
1 answer

This is not possible in Scala. Since Scala has no static notation, you cannot access protected static members of the parent class. This is a known limitation .

The workaround 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 this new class and access the static element through the getter / setter methods:

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

This is ugly, but if you really want to use protected static members, then what you need to do.

+10
source

Source: https://habr.com/ru/post/923263/


All Articles