The Kotlin internal
visibility modifier is used to make your Kotlin members (classes, functions, variables) visible only to the module where they were declared.
For example, you can declare a class and its members as internal
like this:
internal class Helper {
internal val helperVar = 29
internal fun helperFn() = helperVar * 2
}
You may see some tutorials saying that the internal
modifier is similar to Java package-private
modifier, in which a variable or function is only visible to the package where they were declared.
But the internal
modifier is actually different than package-private
because the internal
members can be accessed by other packages in the same module.
In Java, you need to declare a member as public
to allow other packages to access it.
In the following Java code, the highlighted line will cause an error:
package helper;
public class Helper {
int helperVar = 29;
}
// use the Helper class in another package
package test;
import helper.Helper;
public class Test {
void changeHelper() {
Helper helper = new Helper();
helper.helperVar = 7; // ERROR
}
}
The Java compiler will complain that the helperVar
is not public and can’t be accessed from outside the package.
Meanwhile, the internal
modifier doesn’t cause the same error in Kotlin.
Here’s the same example code but in Kotlin:
package helper
class Helper {
internal var helperVar = 29
}
// use the Helper class in another package
package test
import helper.Helper
class Test {
fun changeHelper() {
val helper = Helper()
helper.helperVar = 7 // no error
}
}
The Kotlin code above doesn’t cause any error because the internal
modifier allows you to access the variable as long as it’s in the same module.
A Kotlin module is a set of files that are compiled at the same time during the build process.
If you’re developing an Android application, then most likely all your application code is stored in a single app
module. Gradle will compile your files at the same time, so the internal
modifier is just the same as public
in this case.
The modules in your project are commonly marked by a folder icon with a green dot in Android Studio as shown below:
You can see there are App
and Helper
modules in the MyApplication
project above.
The internal
modifier only makes a difference once you have a multi-module Android application.