Kotlin Visibility Modifiers
Kotlin Visibility Modifiers
Kotlin provides four visibility modifiers that control the accessibility of classes, interfaces, functions, and properties: public, private, protected, and internal. These modifiers define clear boundaries for code access, enabling encapsulation and modular design. Unlike Java, where the default visibility is package private, Kotlin defaults to public when no modifier is specified. By the end of this lesson, you will be able to:
- Describe the scope of each visibility modifier for both top level and member declarations.
- Explain how
internalvisibility maps to the concept of a Gradle module. - Identify how
protecteddiffers from its Java counterpart. - Apply visibility modifiers to enforce encapsulation in library and application code.
Public
The public modifier makes a declaration accessible from anywhere. It is the default visibility in Kotlin, meaning any declaration without an explicit modifier is public.
class UserRepository {
fun getUsers(): List<User> = listOf()
}
Both UserRepository and getUsers() are public. Any code in any module can access them.
Private
The private modifier restricts access depending on the declaration level. For top level declarations (functions, properties, classes declared outside any class), private limits visibility to the file where they are declared. For member declarations inside a class, private limits visibility to that class only.
private val apiKey = "secret" // visible only in this file
class Account {
private var balance = 0 // visible only inside Account
fun deposit(amount: Int) {
balance += amount
}
}
The apiKey property cannot be accessed from other files. The balance property cannot be accessed from outside Account, even from subclasses.
Protected
The protected modifier applies only to class members. It makes a member accessible within the declaring class and its subclasses. Unlike Java, protected in Kotlin does not grant package level access.
open class Base {
protected fun compute(): Int = 42
}
class Derived : Base() {
fun result(): Int = compute() // allowed
}
// val base = Base()
// base.compute() // compile error: protected member
This interview continues for subscribers
Subscribe to Dove Letter for full access to exclusive interviews about Android and Kotlin development.
Become a Sponsor