0
0
KotlinConceptBeginner · 3 min read

What is internal in Kotlin: Understanding Internal Visibility Modifier

internal in Kotlin is a visibility modifier that restricts access to declarations within the same module. It means the code marked as internal can be used anywhere inside the module but is hidden from other modules or projects.
⚙️

How It Works

Think of a Kotlin module as a small neighborhood where all the houses (code files) belong to the same community. When you mark a class, function, or property as internal, it’s like saying "only people living in this neighborhood can visit." No one from outside the neighborhood can see or use it.

This helps keep your code organized and safe by hiding parts that should not be accessed from other modules or projects. It’s more open than private (which limits access to the same file) but more restricted than public (which allows access from anywhere).

💻

Example

This example shows how internal limits access within the same module.

kotlin
internal class InternalClass {
    fun greet() = "Hello from internal class!"
}

fun main() {
    val obj = InternalClass()
    println(obj.greet())
}
Output
Hello from internal class!
🎯

When to Use

Use internal when you want to share code within your module but keep it hidden from other modules or libraries. For example, if you are building a library, you might want some helper functions or classes to be accessible only inside the library but not exposed to the users of the library.

This helps prevent accidental misuse and keeps your public API clean and easy to understand.

Key Points

  • internal limits visibility to the same module.
  • It is more open than private but more restricted than public.
  • Useful for hiding implementation details inside libraries or apps.
  • Helps maintain a clean and safe code structure.

Key Takeaways

internal restricts access to the same module only.
It helps hide code from other modules while allowing internal sharing.
Use it to keep your library or app implementation details private.
It balances between private and public visibility.
Improves code organization and safety by controlling access scope.