Kotlin Getters and Setters

This tutorial is about how to use getters and setters in Kotlin with the help of simple example.

Getters and Setters

Getters are used for getting value of the property and Setters are used for setting the value of the property.

Setters can have visibility modifiers but Getters always have the same visibility as the property.

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

Example:

The following code in Kotlin

class Employee {
    var name: String = ""
    val age: Int = 28
}

is equivalent to

//Default get() and set() functions look like:
class Employee {
    var name: String = ""
        get() = field
        set(value) {
            field = value
        }
    val age: Int = 28
        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 and 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.

When you instantiate object of the Employee class and initialize the name property, it is passed to the setters parameter value and sets field to value.

val employee = Employee()
employee.name = "Arun" // calls set() function

Now, when you access properties (name, age) of the object, you will get field because of the code get() = field.

println("The age of ${employee.name} is ${employee.age}")

Output:

The age of Arun is 28

Custom Getters and Setters

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

Example:

//custom getters and setters
class Employee{
    var name: String = ""
        get() {
            println("get() of name called")
            return field.toString()
        }
        set(value) {
            println("set() of name called")
            if (value.length < 3)
                field = "INVALID NAME"
            else
                field = value
        }
    val age: Int = 28
        get(){
            println("get() of age called")
            return field
        }
}

fun main() {
    val employee = Employee()
    // calls set() function of name property
    employee.name = "Arun" 
    // calls get() function of name and age property
    println("The age of ${employee.name} is ${employee.age}")
}

Output:

set() of name called
get() of name called
get() of age called
The age of Arun is 28
  • The Employee class custom get() and set() function is called for name and custom get() is called for age.
  • The set() function is called internally to set property value using employee.name = “Arun”.
  • The get() function is called internally to get property value using employee.name, employee.age.

Leave a Reply