Start learning free

LESSON 598 OF 639 · OBJECT-ORIENTED PROGRAMMING

Getters and Setters in Kotlin in Kotlin

Lesson

TL ; DR:

A getter reads a private field. A setter changes it, but only to a value the class allows.

In Kotlin, every var property already has a hidden getter and setter. You can replace the setter with your own set(value) block. Other code still writes rex.age, as if it were a plain field.


class Dog(initialAge: Int) {

    var age: Int = initialAge
        set(value) {
            if (value >= 0) {
                field = value
            }
        }
}


Full lesson:

In the Access Modifiers lesson, the field was private and getName() read it. Kotlin has a shorter way. The property stays public, and its own setter checks each new value.

The getter

Reading rex.age runs the hidden getter. It returns the stored value, so you don't write it.

The setter

Write set(value) on the line under the property, indented. Now rex.age = 4 runs it, with value set to 4.

Inside the setter, field is the stored value. Assign to field, not to age. Writing age = value there would run the setter again, forever.

The rule

A dog's age can't be negative. So the setter changes field only when value is 0 or more. After rex.age = -5, the age stays as it was.

The first value, initialAge, goes straight into the property. The setter runs only on later changes.


Your task

The Dog class gets its first age as initialAge. Add a var property age of type Int that starts with it. Give it a setter that ignores negative values.

The code in mainFunction creates rex, then reads and sets rex.age.

Expected output:

Rex is 3
Rex is still 3
Rex is 4
STEP 1 OF 3
    Ctrl + Enter to check

    Getters And Setters in Kotlin

    Keep going with Kotlin500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free