Junior — Middle
What are the access levels for components in Kotlin and how are they used?
sobes.tech AI
Answer from AI
In Kotlin, the following access levels exist for components (classes, functions, properties, etc.):
- public — accessible everywhere. This is the default access level.
- internal — accessible within a single module (compilation unit).
- protected — accessible within the class and its subclasses.
- private — accessible only within the file (for top-level declarations) or within the class (for class members).
Example of usage:
class Example {
private val secret = "private"
protected val semiSecret = "protected"
internal val moduleVisible = "internal"
val publicInfo = "public" // public by default
}
privaterestricts access to the member only within the class.protectedallows subclasses to see the member.internalrestricts access within a single module (e.g., one Gradle module).publicallows the component to be used everywhere.
This helps control encapsulation and the scope of components in an application.