2

In Java package protected access was very handy, because it allowed to write modular code. This is not possible with Kotlin unless you stick all those classes into one file and put Private on all of them or by implementing Internal in a separate Module. But I don't like this solutions. Putting lot of stuff in one file is not readable and another problem is that you cannot test any Method/Class that is not Public. Is there another solution?

  • Does this answer your question? [package protected alternative in kotlin](https://stackoverflow.com/questions/35914095/package-protected-alternative-in-kotlin) – IlyaMuravjov Nov 04 '19 at 10:03
  • I don't get the point on the answer. I think they proposed what I said and I don't whant to do it in this way. – Ines Rodriguez Alonso Nov 04 '19 at 10:51
  • 1
    There is a feature request for package-private visibility or an equivalent: [KT-29227](https://youtrack.jetbrains.com/issue/KT-29227). – Slaw Nov 04 '19 at 17:51

1 Answers1

4

No, package-protected access is not supported.

You should use internal in Kotlin. This restricts access to the same module, a logical unit of files compiled together to an artifact.

The motivation for not providing a package-protected visibility specifier is as follows, from a Kotlin developer:

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.

And you definitely can test methods/classes that have internal access: the tests of a module have full access to internal declarations of that module.

Community
  • 1
  • 1
TheOperator
  • 5,936
  • 29
  • 42
  • This is a good answer. Though I find it hard to accept the Kotlin dev's reasoning.  Yes, it's not _easy_ to access internal methods/classes from outside the module, due to name-mangling; but it's surely _possible_ for a determined attacker.  So it doesn't give any real security.  And with Java 8's sealed packages, package-protected _can_ be securely enforced. – gidds Nov 04 '19 at 13:09
  • 2
    In JVM it's possible to decompile and modify the byte code to do virtually everything; encapsulation is not primarily designed for security. One could argue that using the same package to get access is _too_ easy (i.e. a concern for API design), but I rather believe Kotlin wanted to stay simple, and `internal` is more powerful as it allows you to effectively hide classes from a library's API, whereas Java classes need to be public as soon as they're accessed from another package (in the same module). As a result, several Java `public` classes can be `internal` in Kotlin. – TheOperator Nov 04 '19 at 18:45