In Kotlin, access modifiers are used to set the visible scope of classes, objects, interfaces, constructors, functions, properties, and their setters. Understanding how these modifiers work can help you design your software architecture effectively while maintaining encapsulation and security.
Table of Contents
Public Modifier
The public modifier is the default visibility and is accessible from anywhere in the application. When a class, function, or property is declared as public, it becomes available to any code that can access the location where the declaration itself is visible.
// Public by default
class PublicClass {
fun publicFunction() {
println("This function is public")
}
}
fun main() {
val instance = PublicClass()
instance.publicFunction() // Accessible from anywhere
}
Private Modifier
The private modifier restricts the visibility to the file where it is declared. A class, object, interface, or function marked as private can't be accessed from outside that particular file.
private class PrivateClass {
private fun privateFunction() {
println("This function is private")
}
fun callPrivateFunction() {
privateFunction() // Accessible within the class
}
}
fun main() {
val instance = PrivateClass()
// instance.privateFunction() // This line would cause an error
instance.callPrivateFunction() // This works fine
}
Protected Modifier
The protected modifier is more restricted and can be used within a class and its subclasses. However, unlike Java, you cannot declare top-level definitions (like functions, properties) with protected visibility in Kotlin outside a class or object.
open class SuperClass {
protected fun protectedFunction() {
println("This function is protected")
}
}
class SubClass : SuperClass() {
fun accessProtectedFunction() {
protectedFunction() // Accessible function from subclass
}
}
fun main() {
val instance = SubClass()
instance.accessProtectedFunction()
// instance.protectedFunction() // This line would cause an error
}
Practical Use-Cases
Using the correct visibility modifiers is crucial for maintaining a modular codebase:
- Public: When you intend for certain classes or functions to be a part of the core interface of your module or application.
- Private: Useful for implementation details that are not necessary for the users of the module to see or use.
- Protected: Ideal for scenarios where some functionality needs to be extended but hidden from other parts of the application.
In conclusion, understanding these access modifiers and using them appropriately allows you to create concise, readable, and well-encapsulated Kotlin code. Make sure you choose the right modifier for the right scenario to adhere to good coding practices and data integrity.