Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modifier `protected` is not applicable inside `file` error in Kotlin

Tags:

kotlin

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?

like image 982
Tarun Deep Attri Avatar asked Mar 27 '18 04:03

Tarun Deep Attri


People also ask

What visibility modifier is not available in Kotlin?

In Kotlin the default visibility modifier is public while in Java is package-private. This modifier does not exist in Kotlin.

What modifiers are available in Kotlin?

There are four visibility modifiers in Kotlin: private , protected , internal , and public . The default visibility is public .

What is internal modifier in Kotlin?

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.

Does Kotlin have access modifiers?

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.


1 Answers

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.

like image 145
s1m0nw1 Avatar answered Oct 04 '22 04:10

s1m0nw1