A Java library class I'm using declares
protected getPage(): Page { ... }
Now I want to make a helper Scala mixin to add features that I often use. I don't want to extend the class, because the Java class has different subclasses I want to extend at different places. The problem is that if I use getPage()
in my mixin trait
, I get this error:
Implementation restriction: trait
MyMixin
accesses protected methodgetPage
inside a concrete trait method.
Is there a solution how to make it work, without affecting my subclasses? And why is there this restriction?
So far, I came up with a work-around: I override the method in the trait as
override def getPage(): Page = super.getPage();
This seems to work, but I'm not completely satisfied. Luckily I don't need to override getPage()
in my subclasses, but if I needed, I'd get two overrides of the same method and this work-around won't work.
The problem is that even though the trait extends the Java class, the implementation is not actually in something that extends the Java class. Consider
In the actual bytecode for
B
we seewhich means it just forwards to something called
T$class
, which it turns out isSo the body of the code isn't called from a subclass of
A
at all.Now, with Scala that's no problem because it just omits the
protected
flag from bytecode. ButJava
enforces that only subclasses can call protected methods.And thus you have the problem, and the message.
You cannot easily get around this problem, though the error message suggests what is perhaps the best alternative:
Note the last line.
works.