internal
- Kotlin course
- Intermediate
- Lesson 102/116
- 5 min
Learn module visibility with internal.
internal: Module visibility
The internal visibility modifier states that a definition is visible only inside the same module. A module is a Gradle or Maven unit that is compiled together. public is reachable from anywhere, internal only from inside the module.
internal class Helper {
fun assist() = "help"
}Here the Helper class can be used only within its own module; it cannot be reached from another module. This is useful to hide the internal implementation of a library from its users. private works inside a class, protected in subclasses; internal works at the module level.
The module concept
A module is a unit of code that is compiled together; usually a Gradle subproject. A project can have several modules: an app module, a library module, a test module and so on. internal definitions are visible to all files in the same module; they are invisible to other modules.
// module-a: Helper internal
class Api {
internal fun helper() = "secret"
}Here the Api class is public but the helper method is internal. So Api can be used from another module but helper cannot. This is useful to narrow the surface of an API; external users see only the public parts.
Practice Define an internal class and use it
Define internal class Helper; inside it add fun greet(name: String): String = "Hello, $name!". In main create an instance with val h = Helper(); print the result with println(h.greet("Alex")).
Starter code
// Define the Helper class as internal (visible in the same module)
// greet method: returns Hello, {name}!
// main: create a Helper instance, call greet and println
fun main() {
// write here
}Sample solution
internal class Helper {
fun greet(name: String): String = "Hello, $name!"
}
fun main() {
val h = Helper()
println(h.greet("Alex"))
}Expected output
Hello, Alex!
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Where does internal visibility apply?
- Only in the same module Correct answer
- Only in the same package
- Only in the same file
- Everywhere
Explanation: internal restricts a definition to the same module.
2 Match the visibility modifiers
| Term | Meaning |
|---|---|
public |
Accessible everywhere |
internal |
Same module |
private |
Same class |
protected |
Subclasses |
3 Restrict a class to the module
____ class Helper
internal class Helper
Explanation: internal class Helper restricts the class to the module.