Visibility Modifiers restrict the access of elements like classes, interfaces, functions, properties, constructors, etc to the specific levels. There are 4 types of visibility modifiers in Kotlin – private, public, internal, and protected. Let’s discuss briefly these access modifiers.
Private: This visibility modifier restricts the access of an element within the same file. If the elements are declared private then the classes or objects outside of the file will not be able to access them.
Public: This visibility modifier will allow the elements to be visible for everyone. We will be able to access such elements from anywhere by importing them. By default all the elements in Kotlin are public.
Internal: This visibility modifier will allow the properties or classes or functions to be visible within the same module. The module is the set of files compiled together like the IntelliJ Idea module, maven project, Gradle source set, etc.
Protected: This visibility modifier will allow the elements to be visible within the same file and to its subclasses.
Let’s see how these modifiers are used.
class VisibilityModifier {
// nums array is visible only inside this file VisibilityModifier.kt
private val nums = arrayOf(1, 2, 3, 4, 5)
// printlnElement method is visible only inside the file VisibilityModifier.kt
private fun printlnElement() {
for (i in nums) {
println("Print element: $i")
}
}
// evenPositionElements method is visible only inside this module
internal fun evenPositionElements() {
for(i in nums.indices step 2) {
println("Print element: $i")
}
}
}
// Parent does not have any visibility Modifier specified that mean its public
open class Parent {
// demo is protected, that means it is visible inside this file VisibilityModifiers.kt and its children
open protected fun demo() {
println("Parent.....")
}
}
// Child does not have any modifier specified that means its public
class Child: Parent() {
// demoChildren() does not have any visibility modifier specified that mean its public
fun demoChildren() {
demo()
}
}
Note that the protected modifier cannot be used for the top-level declaration.
You could also declare the access modifier to the constructor using the following syntax.
class A protected constructor() {
}
You cannot specify the modifiers to the local variables.
class A protected constructor() {
fun demo() {
private val num = 0 // throws error
}
}
As you can see in the example, you will get a compile-time error if you use access modifiers to the local variables.
The best practice for coding suggests us to use as many restrictive modifiers as possible so that the behavior of an element cannot be changed from outside. Click on the next button to continue reading.
No responses yet