Table of contents
1.
Introduction
2.
Kotlin Class Functions
3.
Kotlin Visibility Modifier
3.1.
The public modifier
3.2.
The protected modifier
3.3.
The private modifier
3.4.
The internal  modifier
4.
FAQs
5.
Key Takeaways
Last Updated: Mar 27, 2024

Kotlin Class Functions and Visibility Modifiers

Author Vasu Bansal
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In this blog, we will discuss class functions in Kotlin. You will also learn about different types of visibility modifiers present in Kotlin. These modifiers can be applied to the class functions and properties as well. The default behaviour in the absence of modifiers is also discussed in the blog. You will learn the importance of making functions private instead of a simple approach to keeping everything public. 

All these access modifiers are keywords in Kotlin. To learn more about keywords in Kotlin, refer to the blog Kotlin Keywords on the Coding Ninjas Website.

Kotlin Class Functions

We can declare and use functions inside a Kotlin class like other programming languages. To study Kotlin classes and objects in detail, refer to the blog Kotlin Classes and Objects on the Coding Ninjas Website. The following is a sample program to show how functions can be declared inside Kotlin classes.

Code:

// Kotlin program to demonstrate class functions

class Student {
    // Class variables
    var ninja_id: Int = 0
    var ninja_name: String = ""

    // Class function with two arguments
    fun add_details(ninja_id: Int, ninja_name: String){
        this.ninja_id = ninja_id
        this.ninja_name = ninja_name
    }  

    // Class function with no arguments
    fun print_details(){
        println("Ninja ID: ${ninja_id} and Ninja Name: ${ninja_name}")
    }
}

fun main(){
    // Creating object of a class
    var obj = Student()

    // Calling class function which takes two arguments as input
    obj.add_details(1, "Code Studio")
   
    // Calling class function with no arguments as input
    obj.print_details();
}

Output:

Ninja ID: 1 and Ninja Name: Code Studio

Kotlin Visibility Modifier

Visibility modifiers are keywords that limit access to Kotlin classes, interfaces, methods, and properties and their setters. There's no need to make getters visible because they have the same visibility as the property. These modifiers are used at multiple places, such as a class header or method body. Visibility modifiers in Kotlin are categorised into four different types:

  • public
  • protected
  • private
  • internal

The public modifier

The default modifier in Kotlin is public. Unlike Java, public is the default modifier in Kotlin. When we apply public to a class, all the methods and properties in that class become public by default. If the public modifier is applied to a nested element of a class, then all the code which can access the class can also access the element which is declared as public.

Code:

// Kotlin program to demonstrate public access modifier

public class Student {
    // Class variables
    public var ninja_id: Int = 0
    public var ninja_name: String = ""

    // Class function with two arguments
    public fun add_details(ninja_id: Int, ninja_name: String){
        this.ninja_id = ninja_id
        this.ninja_name = ninja_name
    }  
}

fun main(){
    var obj = Student()

    obj.add_details(1, "Code Studio")
}

The protected modifier

The protected modifier in Kotlin restricts access to the declaring class and its subclasses. Unless explicitly altered, a protected declaration in its subclass is also a protected modifier. Protected modifiers can not be declared at the top level. The following program shows example usage of protected modifiers.

Code:

// Kotlin program to demonstrate protected access modifier

open class Student{  
    protected val name: String = "Code Studio"
}  

class Ninja: Student() {
    public fun get_details(){
        println("Name: ${name}")
    }  
}

fun main(){
    var obj = Ninja()
    obj.get_details()
}

Output:

Name: Code Studio

The following program shows how protected variables can be overridden in the derived class.

Code:

// Kotlin program to demonstrate protected access modifier
// Overriding the variable 'name' declared in Student class in the Derived class Ninja

open class Student{  
    open protected var name: String = "Code Studio in Student Class"
}  

class Ninja: Student() {
    override var name: String = "Code Studio in Ninja Class"
    public fun get_details(){
        println("Name: ${name}")
    }  
}

fun main(){
    var obj = Ninja()
    obj.get_details()
}

Output:

Name: Code Studio in Ninja Class

The private modifier

Private modifiers in Kotlin only allow access to code declared within the same scope. It prevents outsiders from accessing the modifier variable or function. In contrast to Java, Kotlin supports numerous top-level declarations in the same file. The following program shows how to use private access modifier in Kotlin.

Code:

// Kotlin program to demonstrate private access modifier

private class Ninja{
    private var name: String = "Code Studio"
   
    fun get_details(){
        println("Name: ${name} from Ninja Class")
    }  
}

fun main(){
    var obj = Ninja() // Create object of the Ninja Class

    obj.get_details() // Get details of the class variables

    println("Name: ${obj.name} in the main function"); // Since name is a private variable of the class Ninja it cannot be accessed outside the class directly
}

Output:

error: cannot access 'name': it is private in 'Ninja'
println("Name: ${obj.name} in the main function"); 
                            ^

The internal  modifier

The internal modifier is a new addition to Kotlin that Java does not support. If a declaration is marked as internal, it will only be available within the same module; attempting to access it from another module will result in an error. A module is a collection of files that have been built together.

internal class TestClass{    
}

FAQs

  1. Where are internal modifiers used frequently?
    Internal modifiers facilitate the creation of APIs and implementations.
     
  2. What is the difference between private and protected access modifiers?
    The protected access modifiers have the same functionality as the private access modifier. The only difference lies in the fact that variables and functions declared protected are also viewable in subclasses.
     
  3. What is the visibility scope of a constructor?
    By default, all constructors are visibility as public. But we can also change the visibility of constructors by adding appropriate access modifiers.

Key Takeaways

Cheers if you reached here!! This blog aimed to introduce you to the concept of class functions and visibility modifiers in Kotlin. Go ahead and read the blog Kotlin Classes and Objects to learn more about classes and objects in Kotlin.  

Yet there is never an end to the learning process, so check out our Android Development Course on the Coding Ninjas Website to learn everything you need to know about Android development and how to design future applications. Until then, good luck!!

Live masterclass