26

I have a Java class that I have ported to Scala, but which still has some Java subclasses implementing abstract functionality.

The original Java had

public abstract class Base {
    ...
    protected abstract Foo getFoo();
}

which was extended

public class Fred extends Base {
    ...
    protected Foo getFoo() {
        return foo;
    }
}

Now when I port Base to Scala

class Base {
    ...
    protected def getFoo(): Foo
}

The compiler complains that

Cannot reduce the visibility of the inherited method ...


Now I understand that because its rules are subtly different, Scala tends to enforce visibility in the compiler rather than the bytecode, so that getFoo is marked public in the javap'd class. But

protected[packagename] def getFoo()

still does not generate a pukka (Java) protected method, although I think that the visibility should be the same.

Is there any way to persuade the Scala compiler to emit a method that Java will consider protected?

2
  • I'll accept an authoritative 'No' Commented Nov 19, 2011 at 0:19
  • Excellent question. I followed the exact same path before reaching this page. Commented Feb 19, 2012 at 21:43

1 Answer 1

2

If you can sandwich Scala between two Java implementations, you could create a Java superclass that only has the desired abstract protected methods, at least until you convert all subclasses to Scala (if this is actually code under your control). But I do hope there's a better way...

EDIT: Another option is to use some kind of bytecode rewriter, like the annotation processing tool.

Sign up to request clarification or add additional context in comments.

1 Comment

It's a despicable plan, but the best I've seen! Actually the subclasses are under my control, so I can just change the implementations of getFoo to public, but this did seem an interesting question.

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.