0
0
Kotlinprogramming~5 mins

Custom getters and setters in Kotlin

Choose your learning style9 modes available
Introduction

Custom getters and setters let you control how a property value is read or changed. This helps keep data safe and correct.

When you want to check or change a value before saving it.
When you want to calculate a value on the fly instead of storing it.
When you want to log or track changes to a property.
When you want to hide how a value is stored from outside code.
Syntax
Kotlin
var propertyName: Type = initialValue
    get() {
        // code to run when reading the property
        return field
    }
    set(value) {
        // code to run when setting the property
        field = value
    }

field is a special keyword that refers to the actual stored value.

You can customize either the getter, the setter, or both.

Examples
This getter returns the name in uppercase every time you read it.
Kotlin
var name: String = ""
    get() = field.uppercase()
This setter makes sure age is never negative.
Kotlin
var age: Int = 0
    set(value) {
        field = if (value >= 0) value else 0
    }
This setter prints a message every time the score changes.
Kotlin
var score: Int = 0
    get() = field
    set(value) {
        println("Score changed from $field to $value")
        field = value
    }
Sample Program

This program shows a person with a name and age. The name is trimmed and shown in uppercase. The age cannot be negative.

Kotlin
class Person {
    var name: String = ""
        get() = field.uppercase()
        set(value) {
            field = value.trim()
        }

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

fun main() {
    val person = Person()
    person.name = "  alice  "
    person.age = -5
    println("Name: ${person.name}")
    println("Age: ${person.age}")
}
OutputSuccess
Important Notes

Use field inside getters and setters to access the actual stored value.

Custom getters can compute values without storing them.

Custom setters can validate or change values before saving.

Summary

Custom getters and setters let you control how properties are read and written.

Use field to access the stored value inside them.

They help keep your data safe and correct.