33

Suppose you're writing an Android project (not a library). All the files are compiled together so... is there any sense to use an internal visibility modifier in this case?

1
  • 2
    Well, you could have different source sets for your app (e.g. src/main, src/release and src/debug). An internal symbol would only be visible within its own source set.
    – Michael
    Commented Dec 20, 2017 at 9:31

2 Answers 2

56

You can have multiple Gradle modules that depend on each other within a single Android application, in that case, internal restricts visibility to within a given module. This could be useful if, for example, you have a separate data module that handles database and network tasks, and you only want to expose a couple interfaces from that module, but not their implementations.

Otherwise, if you're not using multiple modules, and your entire application is just in the default app module, then the internal modifier makes no difference in comparison to the default public visibility.

4
  • 1
    Had to use a protected modifier in Java for that (and deal with a package restriction). Kotlin's internal looks much better Commented Dec 20, 2017 at 10:12
  • What about framework classes like Fragment? They need a public constructor in Java. Since Fragment class it's written in Java, if we override a Fragment in Kotlin and we use "internal" it will work anyways. But is it the way go?
    – Nameless
    Commented Sep 24, 2018 at 16:03
  • There's really no reason to change their visibility to internal instead of using the default public unless you want to hide them from another module.
    – zsmb13
    Commented Sep 24, 2018 at 16:05
  • To hide them from another module could be a case. But also imagine if this fragment extends a "base class" that's generic and it takes some type parameter. If this class type is marked with internal and the Fragment as public, the compiler will complain.
    – Nameless
    Commented Sep 24, 2018 at 16:28
6

No, because you would only have one module. Take a look at the definition.

The internal visibility modifier means that the member is visible within the same module. More specifically, a module is a set of Kotlin files compiled together:

  • an IntelliJ IDEA module;
  • a Maven project; a Gradle source set;
  • a set of files compiled with one invocation of the Ant task.

(Source)

internal only has effect across several modules.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.