In this tutorial, you will learn to use getters and setters in Kotlin with the assistance of an example.

Before you learn about getters and setter, make certain to check Kotlin class and objects.

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

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

In Kotlin, getters and setters are discretionary and are auto-produced in the event that you don’t 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
    }
}

At the point when you start up the object of the Person class and instate the name property, it is passed to the setters parameter value and sets the field to value.

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

Presently, when you access name property of the object, you will get field due to the code get() = field.

println("${p.name}")

Here’s an working example:

fun main(args: Array<String>) {

    val p = Person()
    p.name = "salman"
    println("${p.name}")
}

class Person {
    var name: String = "defaultValue"

    get() = field

    set(value) {
        field = value
    }
}

At the point when you run the program, the output will be:

salman

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


Example: Changing the value of the property

fun main(args: Array<String>) {

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

    val sara = Girl()
    sara.actualAge = 35
    sara.age = 35
    println("Sara: actual age = ${sara.actualAge}")
    println("Sara: pretended age = ${sara.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
}

At the point when you run the program, the output will be:

Sombal: actual age = 15
Sombal: pretended age = 18
Sara: actual age = 35
Sara: pretended age = 32

Here, the actualAge property works as expected.

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


Thanks for reading! We hope you found this tutorial helpful and we would love to hear your feedback in the Comments section below. And show us what you’ve learned by sharing your photos and creative projects with us.


0 Comments

Leave a Reply