Menu

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

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

DEV Community: java·Mayank Kumar·1 day ago
#lWSG8Ns8
#devtojava#devto#dev#internal#class
Long article (1349 words) — no AI summary yet.
Reading 0:00
15s threshold

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 .

Java is different. Its default is package-private, which means "same package only".…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.