Delegation and method visibility

Hello,

I have some little wish concerning delegation. So I’m sharing the idea with this post. To explain the issue I’m referring to the delegation sample in the Kotlin documentation: https://kotlinlang.org/docs/reference/delegation.html

In this sample there is this code:

fun main(args: Array) {
val b = BaseImpl(10)
Derived(b).print() // prints 10
}

Now what I would like to have is the option of fun print() being protected inside class Derived. For class BaseImpl it remains public, of course. The point is that I only want to make use of the BaseImpl.print() method visible inside Derived through delegation, but I don’t want its public visibility to propagate to class Derived, because this breaks the encapsulation of Derived for me. To make sure print cannot be invoked on Derived as in

Derived(b).print()

I have to write a wrapper around Derived that does not declare print another time or at least not as protected which is tedious and repeals the use of delegation in this situation.

So the idea is some way to control the visibility of public methods “obtained” through delegation. I think it would be usefull. What do other people think about this?

Regards, Oliver

Actually delegation has nothing to do with it. Derived implements the Base interface where it is public. Even if you could do what you asked you could still do:

(Derived(10) as Base).print()

The idea is NOT some way to control the visibility of public methods “obtained” through delegation, but controlling visibility of public methods inherited by implementing an interface and the answer is you can’t.

Yeah, I thought about that as well. But from the way I understand it only BaseImpl implements Base whereas Derived does not. I see no reason Derived would have to, because this would render delegation meaningless: I would just use JDK8 default interface methods in Base and had the same effect without having to go through delegation.

That is not the same thing at all and as Kotlin was built to be JDK6 compliant not a possibility