Junior
What are visibility modifiers and how to use them in Kotlin?
sobes.tech AI
Answer from AI
Visibility modifiers in Kotlin define the accessibility of declarations (classes, interfaces, functions, properties) to other parts of the program.
Main visibility modifiers:
public: Visible everywhere. It is the default modifier.internal: Visible only within the same module. A module is considered a set of Kotlin files compiled together.protected: Visible within the class and its subclasses (including members defined in subclasses). Not visible outside the package.private: Visible only within the file where it is declared. For class members, visible only within that class (and its companion object, nested, and inner classes).
Application of modifiers:
- To classes, interfaces, objects, and their constructors.
- To functions, properties, and their getters/setters at the top level (outside classes).
- To class members (nested classes, inner classes, functions, properties).
Example:
// File: example.kt
private const val PRIVATE_CONSTANT = 1 // Visible only in this file
internal fun internalFunction() { // Visible only within the module
println("Internal function called")
}
open class BaseClass {
protected val protectedProperty = "Protected" // Visible in this class and its subclasses
fun publicMethod() { // Visible everywhere (public by default)
println("Public method called")
}
private fun privateMethod() { // Visible only within BaseClass
println("Private method called")
}
}
class DerivedClass : BaseClass() {
fun accessProtected() {
println("Accessing protected property: $protectedProperty") // Access to protected
// privateMethod() // Error: private not visible in subclass
}
}
fun main() {
val base = BaseClass()
base.publicMethod()
// base.protectedProperty // Error: protected not visible outside class and subclasses
val derived = DerivedClass()
derived.accessProtected()
internalFunction()
// PRIVATE_CONSTANT // Error: private at top level visible only in the declaration file
}
| Modifier | Accessibility | Where to use |
|---|---|---|
public |
Everywhere | Default when no other modifier is specified |
internal |
Within a module | For API inside a library or module |
protected |
Inside class and its subclasses (for class members) | To create class hierarchy with inheritance |
private |
Inside file (for top-level); inside class (for members) | To hide implementation details inside a file or class |