Does “internal” visibility modifier in Kotlin work

2019-07-24 07:13发布

问题:

Assuming a module in Kotlin means a project (though it would be good to see what the exact definition of a Kotlin module means .. unclear from docs) ...

Do Kotlin visibility modifiers work yet. I have two projects, a main project and a test project, with different, non overlapping, package paths. The test project is dependent on the main project (in Eclipse). It does not seem to matter whether the interfaces or classes in the main project are marked public or not. In the test project the main project interfaces/classes are visibile/accessible not matter what. The only difference shows up if you mark the main project ones private and then there is a visibility issues. But with or without public it doesn't seem to make any difference.

From what I can make out from the docs, omitting a visibility modifier on an interface or class effects the default visibility, i.e. internal.

回答1:

In current Kotlin the internal visibility modifier is indeed enforced.

In the Kotlin 1.0 Beta RC announcement it says:

Visibility checks were restricted so that, for example, a public declaration can not expose a local, private or internal type. Access to internal declarations is checked in the compiler as well as in the IDE;

And the related release notes has two points supporting this:

  • internal visibility checked in the compiler
  • Names of internal functions and properties are mangled (java interop)

The last point being crucial to help prevent Java from seeing and interacting with internally scoped identifiers.

In Kotlin M14 release announcement it also mentions:

  • internal is checked in the compiler (not only IDE)
  • protected and internal members are prohibited in interfaces

And further back in time the Kotlin M13 release announcement also shows:

  • Access to internal is now checked outside of a module (details below);
  • the default visibility (no modifier) is changed from internal to public,
  • we finally enabled the checks that reject usages of internal declarations outside a module.

So it clearly is functional and working.



回答2:

One thing worth to note is that it works only for Kotlin modules but accessing "internal" declaration from Java modules is still possible, though it shows inspection report (warning).

https://youtrack.jetbrains.com/issue/KT-19053



标签: kotlin