Kotlin Getters and Setters

Before you learn about getters and setter, be sure to check Kotlin class and objects.

In programming, getters are used for getting value of the property. Similarly, setters are used for setting value of the property.

In Kotlin, getters and setters are optional and are auto-generated if you do not create them in your program.


How getters and setters work?

The following code in Kotlin

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

is equivalent to

class Person {
    var name: String = "defaultValue"

    // getter
    get() = field

    // setter
    set(value) {
        field = value
    }
}

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

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

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

println("${p.name}")

Here's an 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 you run the program, the output will be:

jack

This is how getters and setters work by default. However, you can change value of the property (modify value) using getters and setters.


Example: Changing value of the property

fun main(args: Array<String>) {

    val maria = Girl()
    maria.actualAge = 15
    maria.age = 15
    println("Maria: actual age = ${maria.actualAge}")
    println("Maria: pretended age = ${maria.age}")

    val angela = Girl()
    angela.actualAge = 35
    angela.age = 35
    println("Angela: actual age = ${angela.actualAge}")
    println("Angela: pretended 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 you run the program, the output will be:

Maria: actual age = 15
Maria: pretended age = 18
Angela: actual age = 35
Angela: pretended age = 32

Here, the actualAge property works as expected.

However, there is additional logic is setters to modify value of the age property.

Did you find this article helpful?