Visibility modifiers in Kotlin are essential tools for controlling access to classes, functions, and properties. They help enforce encapsulation and define the scope of code elements.
Kotlin provides four visibility modifiers:
To apply a visibility modifier, place it before the declaration:
public class MyPublicClass
private fun myPrivateFunction()
protected var myProtectedProperty = 0
internal object MyInternalObject
public class User(private val id: Int, internal val name: String) {
protected fun validate() {
// Validation logic
}
}
In this example:
User
class is public (accessible everywhere)id
property is private (only accessible within the class)name
property is internal (accessible within the same module)validate()
function is protected (accessible in subclasses)// File: utils.kt
internal fun calculateTax(amount: Double): Double {
// Tax calculation logic
}
private const val TAX_RATE = 0.2
Here, calculateTax()
is internal and can be used within the same module, while TAX_RATE
is private and only accessible within the file.
Understanding visibility modifiers is crucial when working with Kotlin Classes and Kotlin Inheritance. They also play a significant role in Kotlin Interfaces and Kotlin Objects.
Visibility modifiers in Kotlin provide fine-grained control over code accessibility. By using them effectively, you can create more maintainable and secure code structures. Remember to always consider the appropriate visibility level for each declaration in your Kotlin projects.