Signup/Sign In

Kotlin Getter and Setter Functions

In this tutorial, we will learn about getters and setters in Kotlin used for getting class properties values and setting class properties values. In the previous tutorials, we saw that the properties declared inside a class are accessed using . operator. If we have a class Employee with the following definition:

class Employee{
    var salary: Int = 0
    var name: String = ""
}

We can create an object of Employee class and access properties using . operator:

val employee = Employee()
employee.salary = 340000
employee.name = "Ninja"
println("The salary of ${employee.name} is ${employee.salary}")

Whenever we try to get or set the value of a property, properties are not directly accessed. The getter and setter functions are called for getting and setting the value of a property.

What are getters and setters?

Getter and Setter are the functions that are generated by default for each class property by Kotlin. They are used to access the property.

If we try to call classname.property = value the set() function is called internally and if we try to get property value using classname.property the get() function is called internally.

Why Getter and Setter function?

It is a good practice to not expose the variables of a class outside it. If you are coming from Java then you must have declared class properties as private and created getter and setter methods for it. Kotlin by default provides this feature.

Getter and Setter in Kotlin

Default get() and set() functions look like:

class Person{
    var name: String = ""
        get() = field
        set(value) {
            field = value
        }
    val age: Int = 0
        get() = field
}

Properties declared with var have both get() and set() functions. But the properties declared with val have only get() function. This is because values to val cannot be reassigned.

The field keyword is used to represent the variable. The value is used to represent the value to be assigned to the variable. It can be changed also. These get() and set() functions are redundant as Kotlin provides them by default.

Define Custom Getters and Setters

We can also provide custom get() and set() function:

class Person{
    var name: String = ""
        get() {
            println("Inside get() of name")
            return field.toString()
        }
        set(value) {
            println("Inside set() of name")
            if (value.length < 3)
                field = "INVALID NAME"
            else
                field = value
        }
    val age: Int = 18
        get(){ 
            println("Inside get() of age")
            return field
        }
}

Here we've created custom get() and set() function for name and custom get() for age. Let us create object of this class and print the output:

fun main() {
    val person = Person()
    person.name = "Ninja"       // calls set() function
    println("The age of ${person.name} is ${person.age}")        // calls get() functions 
} 


Inside set() of name
Inside get() of name
Inside get() of age
The age of Ninja is 18

Summary

In this tutorial, we discussed getters and setters functions in Kotlin and created custom getters and setters. Using custom getters and setters, we can add validations before assigning values to properties or perform some operation on the values too. We'll discuss inheritance in the next tutorial.



About the author:
I'm a writer at studytonight.com.