English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Kotlin Getters and Setters

In this article, you will learn how to use getters and setters in Kotlin with the help of an example.

Before learning about getters and setters, it is best to have already understoodKotlin classes and objects.

In programming, getters are used to get the value of a property. Similarly, setters are used to set the value of a property.

In Kotlin, getters and setters are optional, and if they are not created in the program, they will be automatically generated.

How do getters and setters work?

The following code in Kotlin

class Person {
    var name: String = "defaultValue"
}

equivalent to

class Person {
    var name: String = "defaultValue"
    // getter
    get() = field
    // setter
    set(value) {
        field = value
    }
}

When instantiating an object of the Person class and initializing the name property, it will pass the value to the setters parameter and set field to value.

val p = Person()
p.name = "jack"

Now, when you access the name property of the object, since the code get()=field, you will get field

println("${p.name}")

Here is a working example:

fun main(args: Array<String>) {
    val p = Person()
    p.name = "jack"
    println("${p.name}")
}
class Person {
    var name: String = "defaultValue"
    get() = field
    set(value) {
        field = value
    }
}

When running the program, the output is:

jack

By default, this is how getters and setters work. However, you can use getters and setters to change the value of properties (modify the value).

Example: Change the value of properties

fun main(args: Array<String>) {
    val maria = Girl()
    maria.actualAge = 15
    maria.age = 15
    println("Maria: Actual Age = ${maria.actualAge}")
    println("Maria: Virtual Age = ${maria.age}")
    val angela = Girl()
    angela.actualAge = 35
    angela.age = 35
    println("Angelo: Actual Age = ${angela.actualAge}")
    println("Angelo: Virtual Age = ${angela.age}")
}
class Girl {
    var age: Int = 0
    get() = field
    set(value) {
        field = if (value < 18)
            18
        else if (value >= 18 && value <= 30)
            value
        else
            value-3
    }
    var actualAge: Int = 0
}

When running the program, the output is:

Maria: Actual Age = 15
Maria: Virtual Age = 18
Angelo: Actual Age = 35
Angelo: Virtual Age = 32

Here, the ActialAge property works as expected.

However, there is other logic that can be modified to set the program setter and change the value of the age property.