Intern
What are access modifiers?
sobes.tech AI
Answer from AI
Access modifiers in Kotlin define the visibility of declarations (classes, interfaces, functions, properties). They control where the element can be used.
Available modifiers:
public(default): Visible from anywhere.private: Visible only within the containing block (class, file).protected: Visible within the class and all its subclasses. Not accessible for top-level members (defined outside the class).internal: Visible only within the same module.
Example:
// file: Example.kt
package com.example.app
private const val PRIVATE_CONSTANT = 1 // Visible only in this file
public class PublicClass { // Visible from anywhere
private var privateProperty = 0 // Visible only inside PublicClass
protected open fun protectedMethod() { // Visible inside PublicClass and its subclasses
// ...
}
internal fun internalMethod() { // Visible only within the module ComExampleApp
// ...
}
}
open class BaseClass {
protected val protectedValue = 5 // Visible inside BaseClass and subclasses
}
class DerivedClass : BaseClass() {
fun useProtectedValue() {
println(protectedValue) // Access to protectedValue from subclass
}
}