# What Is the Difference Between public, private, protected and internal in Kotlin?

> **In short:** A visibility modifier decides who can use a class, function or property. `public` is the default and means everyone. `private` means the same class, or the same file for top-level code. `protected` means the class and its subclasses. `internal` means the same module.

Say your app has a `:network` module. Inside it is an `ApiClient` class that the rest of the app should use, and a `buildUserAgent()` helper that only `ApiClient` needs. If you write no modifier, both are public. One day a screen in `:feature:checkout` calls the helper directly. Later you change the helper, and that screen breaks.

Visibility modifiers stop this. This post covers the four modifiers, what a "module" is, and what `internal` turns into in bytecode, including a surprise for Java callers.

## What is the default visibility in Kotlin?

`public`. If you don't write a modifier, the [declaration is visible everywhere](https://kotlinlang.org/docs/visibility-modifiers.html#packages).

Java is different. Its default is package-private, which means "same package only". Kotlin has no package-private at all.

If you build a library, you can turn on [explicit API mode](https://kotlinlang.org/docs/whatsnew14.html#explicit-api-mode-for-library-authors). Then the compiler asks you to write `public` on purpose, so nothing becomes public by accident.

## What does private mean?

It depends on where you write it:

- Inside a class: only that class can use it.
- At the top of a file: only that file can use it.

```kotlin
// EmailUtils.kt
private fun normalize(email: String) = email.trim().lowercase()

fun isSameEmail(a: String, b: String) = normalize(a) == normalize(b)
```

Any other file that calls `normalize()` fails, even in the same package:

```
cannot access 'fun normalize(email: String): String': it is private in file.
```

Use top-level `private` for small helpers that belong to one file. If two files need the helper, `private` is too small. That's where `internal` comes in.

You can also make only the setter private, with `var count = 0` and `private set` on the next line. Everyone can read `count`, but only the class can change it.

## What does protected mean?

`protected` is like `private`, but [subclasses can use it too](https://kotlinlang.org/docs/visibility-modifiers.html#class-members).

```kotlin
open class BaseScreen {
    protected open fun title() = "Untitled"
    fun render() = "<h1>${title()}</h1>"
}

class HomeScreen : BaseScreen() {
    override fun title() = "Home"  // still protected
}
```

`HomeScreen` can override and call `title()`. Other code can't, even in the same file. And when you override a protected member, it stays protected unless you change it.

You can't use `protected` at the top of a file, because there is no class to extend. The compiler says `modifier 'protected' is not applicable to 'top level function'`.

There is one Java difference. In Java, `protected` also opens a member to the whole package. In Kotlin it doesn't. But in bytecode, it is still Java's `protected`, so a Java class in the same package [can call it](https://kotlinlang.org/docs/java-to-kotlin-interop.html#visibility).

## What does internal mean?

`internal` means "anyone in the same module can use it". A [module](https://kotlinlang.org/docs/visibility-modifiers.html#modules) is a set of Kotlin files compiled together. On Android, think of each Gradle module: `:app`, `:core:network`, `:feature:checkout`.

So `buildUserAgent()` should be `internal`. `ApiClient` can call it, any file in `:network` can call it, and `:feature:checkout` gets an error:

```
cannot access 'fun buildUserAgent(version: String): String': it is internal in file.
```

Unit tests in `src/test` of the same module can still use `internal` code. The Kotlin docs make this exception for the test source set.

One more rule: a public function can't hand out an internal type. If `TokenStore` is internal, `fun tokens(): TokenStore` must be internal too. Otherwise you get `'public' function exposes its 'internal' return type`.

## What does internal look like in bytecode?

The JVM has no idea what a Kotlin module is. It only knows public, protected, package-private and private. So the compiler makes `internal` code `public` in bytecode.

Here is a file in a module named `network`:

```kotlin
internal fun buildUserAgent(version: String) = "MyApp/$version"

class ApiClient {
    internal fun sendRequest(path: String) = "GET $path"
}
```

And here is the decompiled Java (Kotlin 2.4.21, Vineflower):

```java
public final class NetworkKt {
    public static final String buildUserAgent(String version) { ... }
}

public final class ApiClient {
    public final String sendRequest$network(String path) { ... }
}
```

Three things to notice:

1. Both are `public`.
2. The top-level function keeps its own name. Only the class member gets a new one.
3. The member's new name ends with `$` and the module name. The compiler [renames internal members](https://kotlinlang.org/docs/java-to-kotlin-interop.html#visibility) so that two modules can't override or clash with each other by accident. A dash in the module name becomes an underscore.

An `internal class` also becomes a `public` class. Its public members keep their names. Only its `internal` members get the `$network` ending.

![Diagram: who can see it. Nested boxes: private inside a class, private at top level inside a file, internal inside a module, public everywhere; protected reaches subclasses, even in another module. On the JVM, internal becomes public, and internal class members get a $module ending.](https://imayankkumar.com/blog/kotlin-visibility-modifiers/kotlin-visibility-modifiers.png)

## Can Java code call internal functions?

Yes. The Java compiler doesn't read Kotlin's rules. Only the Kotlin compiler checks `internal`. From a Java file in another module, both of these compile:

```java
String ua = NetworkKt.buildUserAgent("2.0");      // plain name
new ApiClient().sendRequest$network("/home");      // ugly name, still works
```

The `$network` name is only a "keep out" sign. The top-level function doesn't even have that. If Java callers must not use it, add [`@JvmSynthetic`](https://kotlinlang.org/api/core/kotlin-stdlib/kotlin.jvm/-jvm-synthetic/):

```kotlin
// Almost right: other Kotlin modules can't call it, but Java can
internal fun buildUserAgent(version: String) = "MyApp/$version"

// Right, when Java must stay out too
@JvmSynthetic
internal fun buildUserAgent(version: String) = "MyApp/$version"
```

With `@JvmSynthetic`, the Java compiler can't see the function and gives `cannot find symbol`. Kotlin code in the same module calls it as before.

| Feature | private | protected | internal | public |
| --- | --- | --- | --- | --- |
| Who can use it? | Same class, or same file at top level | The class and its subclasses | The same module | Everyone |
| At the top of a file? | Yes | No | Yes | Yes |
| The default? | No | No | No | Yes |
| In bytecode | `private` (a top-level class: package-private) | `protected` | `public` (members get `$module`) | `public` |
| Can Java call it? | No | Yes, from subclasses and the same package | Yes | Yes |
| Good for | Helpers for one class or file | Hooks for subclasses | Code shared inside one module | Your module's API |

## Frequently asked questions

**Does Kotlin have package-private?**
No. If only one file needs a helper, make it `private` at the top of that file. If several files need it, make it `internal`.

**Can unit tests use internal code?**
Yes, tests in `src/test` of the same module can. Gradle tells the Kotlin compiler that the test code is a "friend" of the main code. Tests in another module can't.

**Is private enough to hide an API key?**
No. Visibility stops mistakes when you compile. It doesn't hide anything from someone who decompiles your APK or uses reflection.

## What should you remember?

Start every declaration as `private` and open it only when you need to. Use `protected` for hooks you want subclasses to change. Use `internal` for code shared inside one Gradle module. Keep `public` for the API other modules should use. And remember that `internal` is checked by the Kotlin compiler only: in bytecode it is `public`, and Java can call it.

If you want to test yourself, try the [visibility modifiers interview questions](https://imayankkumar.com/interview/kotlin-visibility-modifiers/). This post is the thirteenth topic in Stage 1 of my [Android roadmap](https://imayankkumar.com/roadmap/). The previous one is [lazy vs lateinit](https://imayankkumar.com/blog/kotlin-lazy-vs-lateinit/).

Which public function in your code should really be `private` or `internal`?

---

*This post first appeared on* [*imayankkumar.com*](https://imayankkumar.com/blog/kotlin-visibility-modifiers/)*, where you'll find new posts first.*

