Visibility: internal and friends

Kotlin language Junior Kotlin 2.0+ API 24+ Reviewed By Best Latest Apps

Pick the fix

Another feature module keeps using FeedMapper directly, bypassing the repository. How do you stop that?

Options
Hint 1 of 1

Which modifier means 'only this module'?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A Mark FeedMapper internal so only its own module can use it

Correct. internal limits it to the Gradle module.

Why not the others?
  • B Mark it private. Then the repository in other files of the same module can't use it either.
  • C Mark it protected. protected only applies to class members.
  • D Add a comment asking people not to use it. Visibility is enforced by the compiler; comments aren't.

30-second answer

public (the default) is visible everywhere, private inside the file or class, protected in the class and subclasses, and internal inside the same Gradle module. In a modular app, internal hides implementation classes so other modules can only use the public API, which keeps module boundaries real and builds faster.

Practise saying it · 25 s. No recording, just a timer

Explain Kotlin visibility modifiers.

Say your answer out loud, then check which of these points you covered:

  • public, private, protected, internal
  • internal = same module
  • Hides implementation between modules
  • Explicit API mode for libraries

Deep dive

Top-level private means visible only in that file.

Test source sets in the same module can see internal declarations.

Java sees internal as public with a mangled name, so it isn't a hard barrier from Java.

Use the explicit API mode in library modules to force a visibility on every public declaration.

Common mistakes

  • Leaving every class public in a feature module.
  • Thinking internal means package-private.
  • Making things public just for tests.

Senior take & follow-ups

Connect internal to modularisation and build times.

Follow-up questions

Think of your answer first, then open the hint.

  1. What's explicit API mode?

    Show hint

    A compiler setting that requires visibility and return types on public API.

  2. Can tests see internal members?

    Show hint

    Yes, tests in the same module can.

Suggest a fix if something here is wrong or out of date.