Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Package protected alternative in Kotlin

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

like image 937
vach Avatar asked Mar 10 '16 10:03

vach


People also ask

What is protected modifier in Kotlin?

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.

Which access specifier has package level visibility in Kotlin?

In Kotlin the default visibility modifier is public while in Java is package-private.

Can a class be protected in Kotlin?

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.

What is the default visibility modifier in Kotlin?

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


1 Answers

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 file
  • internal to restrict visibility to the module

At this point, there is no other option for visibility restriction.

like image 95
hotkey Avatar answered Sep 22 '22 08:09

hotkey