I have a class whose declaration is like :
class NetworkManagerImpl : NetworkManager { }
I wanted to make the class protected so that it is visible inside package only. But when i add protected in front of class like :
protected class NetworkManagerImpl : NetworkManager { }
It gives error as Modifier protected
is not applicable inside file
How to fix this error or more importantly how to make an entire class(Top level) protected?
In Kotlin the default visibility modifier is public while in Java is package-private. This modifier does not exist in Kotlin.
There are four visibility modifiers in Kotlin: private , protected , internal , and public . The default visibility is public .
The internal visibility modifier means that the member is visible within the same module. More specifically, a module is a set of Kotlin files compiled together: an IntelliJ IDEA module; a Maven project; a Gradle source set; a set of files compiled with one invocation of the Ant task.
In Kotlin, visibility modifiers are used to restrict the accessibility of classes, objects, interfaces, constructors, functions, properties, and their setters to a certain level. No need to set the visibility of getters because they have the same visibility as the property.
As written in the docs, there is no protected
modifier for top-level entities like classes.
Here’s a statement coming from a Kotlin team member:
The motivation for not having package protected access is very simple: it does not provide any real encapsulation. Any other module in the system can define classes in the same package as your complex independent component and get full access to its internals. On the other hand, classes with internal visibility cannot be accessed from any module other than the one where they are defined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With