How to change the access level of inherited methods in Scala

I am expanding an existing library (let's call it Lib ), which I cannot modify directly.

Is there a way to make some methods from Lib private so that they cannot be accessed outside of subclasses?

For example, if I have:

 class A extends Lib { def fun(i: int) = someLibFunction(i) //someLibFunction is inherited from Lib } 

how can I make someLibFunction private in A, even though it was public / protected in Lib?

+4
source share
1 answer

This violates the basic foundation of object-oriented programming - you can use a subclass wherever a superclass (polymorphism) was expected.

If it were allowed to narrow the visibility of the method (for example, from public to private ), client code receiving an instance of Lib would not be allowed to receive A extends Lib . The client code expects someLibFunction() be available, and the subclass will not be able to modify this contract.

At the same time, neither Scala nor an object-oriented language can narrow the visibility of any method when subclassing. Please note that the extension of visibility (for example, from protected to public is quite possible).

In other words, you are not extending an existing API (library). You create a completely different API (library) that has a different contract.

Final example: you have a Vehicle class that has capacity() and can drive() . Car can expand Vehicle by adding new features like refuel() . But Container cannot expand Vehicle and hide driving opportunities. Container may contain Vehicle (or vice versa), and Container and Vehicle may also have a common parent type, for example CanHoldCargo .

+10
source

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


All Articles