Open In App

Kotlin Visibility Modifiers

Last Updated : 09 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In Kotlin, visibility modifiers are used to control the visibility of a class, its members (properties, functions, and nested classes), and its constructors. The following are the visibility modifiers available in Kotlin:

  1. private: The private modifier restricts the visibility of a member to the containing class only. A private member cannot be accessed from outside the class.
  2. internal: The internal modifier restricts the visibility of a member to the same module. A module is a set of Kotlin files compiled together.
  3. protected: The protected modifier restricts the visibility of a member to the containing class and its subclasses.
  4. public: The public modifier makes a member visible to any code. This is the default visibility for members in Kotlin.

In Kotlin, visibility modifiers are used to restrict the accessibility of classes, objects, interfaces, constructors, functions, properties, and their setters to a certain level. No need to set the visibility of getters because they have the same visibility as the property.
There are four visibility modifiers in Kotlin. 

If there is no specified modifier then by default it is public. Let’s start discussing the above modifiers one by one.

1. Public Modifier

In Kotlin, the default modifier is public. It is possibly the most frequently used modifier in the entire language and there are additional restrictions on who can see the element being modified. Unlike Java, in Kotlin there is no need to declare anything as public – it is the default modifier, if we don’t declare another modifier – public works the same in Kotlin, as in Java. When we apply the public modifier to top-level elements – classes, functions or variables declared directly inside a package, then any other code can access it. If we apply the public modifier to a nested element – an inner class, or function inside a class – then any code that can access the container can also access this element.

Kotlin




// by default public
class A {            
    var int = 10
}
 
// specified with public modifier
public class B {    
    var int2 = 20
    fun display() { 
    println("Accessible everywhere")        
    }
}


Here, Class A and B are accessible from anywhere in the entire code, the variables int, int2, and the function display() are accessible from anything that can access classes A and B.

2. Private Modifier

In Kotlin, private modifiers allow only the code declared inside the same scope, access. It does not allow access to the modifier variable or function outside the scope. Unlike Java, Kotlin allows multiple top-level declarations in the same file – a private top-level element can be accessed by everything else in the same file.

Kotlin




// class A is accessible from same source file
private class A {
    private val int = 10
    fun display()
    {
        // we can access int in the same class
        println(int)  
        println("Accessing int successful")
    }
}
fun main(args: Array<String>){
    var a = A()
    a.display()
    // can not access 'int': it is private in class A
    println(a.int
}


Output: 

Cannot access 'int': it is private in 'A'

Here, Class A is only accessible from within the same source file, and the int variable is only accessible from the inside of class A. When we tried to access int from outside the class, it gives a compile-time error. 

3. Internal Modifier

In Kotlin, the internal modifier is a newly added modifier that is not supported by Java. Marked as internal means that it will be available in the same module, if we try to access the declaration from another module it will give an error. A module means a group of files that are compiled together.

Note: Internal modifier benefits in writing APIs and implementations. 

Kotlin




internal class A {
}
public class B {
    internal val int = 10
    internal fun display() {
    }
}


Here, Class A is only accessible from inside the same module. The variable int and function display() are only accessible from inside the same module, even though class B can be accessed from anywhere. 

4. Protected Modifier

In Kotlin, the protected modifier strictly allows accessibility to the declaring class and its subclasses. The protected modifier can not be declared at the top level. In the below program, we have accessed the int variable in the getvalue() function of the derived class. 

Kotlin




// base class
open class A {
      // protected variable
    protected val int = 10
}
 
// derived class
class B: A() {
    fun getvalue(): Int {
          // accessed from the subclass
        return int        
    }
}
 
fun main(args: Array<String>) {
    var a = B()
    println("The value of integer is: "+a.getvalue())
}


Output: 

The value of integer is: 10

Overriding of Protected Modifier

We need to mark the protected variable or function using an open keywords to override in the derived class. In the below program, we have overridden the int variable. 

Kotlin




// base class
open class A {
     // protected variable
    open protected val int = 10
 
}
 
// derived class
class B: A() {
   override val int = 20
    fun getvalue():Int {
          // accessed from the subclass
        return int        
    }
}
 
fun main(args: Array<String>) {
    var a = B()
    println("The overridden value of integer is: "+a.getvalue())
}


Output: 

The value of integer is: 20

Constructor Visibility

By default constructors are public, but we can also change the visibility of a constructor by using the modifiers.  

class A (name : String) {
      // other code
}

We must explicitly specify this by using the constructor keyword whilst changing the visibility.  

class A private constructor (name : String) {
      // other code
}

Advantages of using visibility modifiers in Kotlin:

  1. Encapsulation: By restricting the visibility of the members of a class, you can enforce the principle of encapsulation and ensure that the internal state of the class remains hidden from the outside world.
  2. Modularity: By controlling the visibility of the members of a class, you can create modular components that can be easily reused and maintained.
  3. Abstraction: By hiding the implementation details of your classes behind public interfaces, you can create an abstraction layer that makes your code more maintainable and less prone to bugs.

Disadvantages of using visibility modifiers in Kotlin:

  1. Complexity: Using visibility modifiers can make your code more complex, especially if you have many classes and members with different visibility levels.
  2. Overhead: Restricting the visibility of members can add some overhead to your code, as the compiler has to perform additional checks to enforce the visibility rules.

Reference:

A popular book for learning Kotlin is “Kotlin in Action” by Dmitry Jemerov and Svetlana Isakova. This book provides a comprehensive introduction to the Kotlin programming language, including its syntax, libraries, and best practices, with many hands-on examples and exercises.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads