In Java, we have the package protected (default) modifier for classes, which allows us to have many classes in a single package but exposes only a few and keeps the logic encapsulated.
With Kotlin this doesn't seem to be the case. If I want a few classes to be visible to each other but no further, I have to use a private modifier which limits visibility to a single file.
So if you want 10 classes in a package but only one of them to be public, you'd have to have one huge file with all the classes in it (and private
all over the place).
Is this normal practice or there is a way to achieve some similar modularity in Kotlin?
I don't understand: if they have the notion of a package, why did they get rid of package protected access?
Update: We might have package protected visibility after all
see the discussion here
Update: If you read through the discussion and still think this is a must-have feature for the language, please vote here
The protected modifier in Kotlin means that it is strictly accessible only by the declaring class and subclasses. This is the same as most people expect Java to work, but subtly different from how Java works.
In Kotlin the default visibility modifier is public while in Java is package-private.
In Kotlin, the protected modifier strictly allows accessibility to the declaring class and its subclasses. The protected modifier can not be declared at the top level.
There are four visibility modifiers in Kotlin: private , protected , internal , and public . The default visibility is public .
Kotlin, compared to Java, seems to rely on packages model to a lesser degree (e.g. directories structure is not bound to packages). Instead, Kotlin offers internal
visibility, which is designed for modular project architecture. Using it, you can encapsulate a part of your code inside a separate module.
So, on top level declarations you can use
private
to restrict visibility to the fileinternal
to restrict visibility to the moduleAt this point, there is no other option for visibility restriction.
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