Junior — Middle
Can you explain the purpose and use of the protected access modifier in Kotlin?
sobes.tech AI
Answer from AI
In Kotlin, the access modifier protected means that the class member is accessible within the class itself and in its subclasses (inheritants). Unlike Java, in Kotlin protected does not grant access to the member from other classes in the same package.
Example of usage:
open class Parent {
protected val secret = "This is a protected property"
}
class Child : Parent() {
fun revealSecret() = secret
}
fun main() {
val child = Child()
println(child.revealSecret()) // Works
// println(child.secret) // Error: secret is not accessible outside the class and its subclasses
}
Thus, protected is used to restrict access, allowing inheritors to use and modify protected members, but hiding them from external code.