Visibility modifiers in Kotlin are keywords that set the visibility of classes, objects, interfaces, constructors, functions, and properties.
Types of Visibility Modifiers
There are Four types of visibility modifiers in Kotlin.
- Private
- Protected
- Public
- Internal
The purpose of modifiers is to provide accessibility to classes, objects, functions, etc.
Basically, there is no need to set modifiers for getters as they have the same visibility as their properties.
Public Modifier is the default modifier in Kotlin.
Public Modifier
It is the default visibility modifier in Kotlin.
Classes, variables, and interfaces are visible everywhere which are public. It is also a frequently used modifier.
Generally used when no need to implement restrictions on field function and variables.
For Example :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
//Specified that class is public. public class exampleOne { var a = 20 fun printValue() { println("Accessible everywhere") } } //Below class is by defualt Public class ExampleTwo { var int = 10 } |
Private Modifier
Private modifiers are only allowed within the block in which property is declared. It does not allow outside access.
A private package can only be accessible within that specific file. Generally used when implementing more restrictions on field function and variables.
For Example :
1 2 3 4 5 |
private class Example { private val someVariable = 1 private printSomething() { } } |
Protected Modifier
Protected modifier with class and interface only visible to its class or subclass
An overridden, protected declaration in its subclass will also be a protected modifier until we change explicitly. Generally used when implementing more restrictions on field function and variables.
Internal Modifier
The internal modifier makes the field visible only inside the module. Error Will through if we access any field outside the module. Generally used with Api-related Work.
For Example
1 2 3 4 5 6 |
internal class Example{ internal val a = 5 internal fun getValue(){ } } |
Conculusion
In this blog, we have discussed about the Visibility modifiers in Kotlin
Thank you for reading!!