Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change access level of inherited methods in Scala

Tags:

scala

I am extending an existing library (lets call it Lib) that I cannot modify directly.

Is there any 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, despite it being public/protected in Lib?

like image 381
Rand Avatar asked Dec 21 '22 20:12

Rand


1 Answers

This would break the basic foundation of object-oriented programming - that you can use subclass everywhere where super class was expected (polymorphism).

If it was allowed to narrow down the visibility of a method (e.g. from public to private) client code receiving an instance of Lib would not be allowed to receive A extends Lib. Client code expects someLibFunction() to be accessible and subclass cannot change that contract.

That being said neither Scala nor any object-oriented language is allowed to narrow down the visibility of any method when subclassing. Note that widening the visibility (e.g. from protected to public is perfectly possible).

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

Final example: you have a Vehicle class that has a capacity() and can drive(). Car can extend Vehicle by adding some new capabilities like refuel(). But Container cannot extend Vehicle and hide driving capability. Container can contain Vehicle (or vice-versa), also Container and Vehicle might have common parent like CanHoldCargo.

like image 129
Tomasz Nurkiewicz Avatar answered Jan 17 '23 16:01

Tomasz Nurkiewicz