Package protected alternative in Kotlin

vach picture vach · Mar 10, 2016 · Viewed 13.3k times · Source

In Java, we have package protected (default) modifier for classes, which allows us to have many classes in a single package but exposes only a few and keep the logic encapsulated.

With Kotlin this seems not to be the case, if I want to have few other classes that shall be visible to each other, but not further I have to use a private modifier which limits visibility to a single file. So essentially if you had 10 classes in a package and only one of those were public now you'll 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 feature for the language, please vote here

Answer

hotkey picture hotkey · Mar 10, 2016

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.