Site icon C1CTech

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
}

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
Exit mobile version