0
0
KotlinConceptBeginner · 3 min read

Custom Getter and Setter in Kotlin: What They Are and How to Use

In Kotlin, custom getter and setter let you define special code that runs when you read or write a property. They allow you to control how a property value is accessed or changed beyond the default behavior.
⚙️

How It Works

Think of a property in Kotlin like a box that holds a value. Normally, when you open the box (get the value) or put something inside (set the value), Kotlin does this directly without extra steps. But with custom getters and setters, you add a little helper that runs each time you open or close the box.

This helper can check, change, or log the value before giving it to you or saving it. For example, you might want to always return the value in uppercase or prevent setting a negative number.

Under the hood, Kotlin lets you write a small block of code for the getter or setter of a property. When you get the property, the getter code runs. When you set it, the setter code runs. This way, you control exactly what happens on access or assignment.

💻

Example

This example shows a property with a custom getter that returns the name in uppercase and a custom setter that only accepts non-empty names.

kotlin
class Person {
    var name: String = ""
        get() = field.uppercase()
        set(value) {
            if (value.isNotBlank()) {
                field = value
            } else {
                println("Name cannot be empty")
            }
        }
}

fun main() {
    val person = Person()
    person.name = "alice"
    println(person.name)  // Prints: ALICE
    person.name = ""    // Prints: Name cannot be empty
    println(person.name)  // Prints: ALICE
}
Output
ALICE Name cannot be empty ALICE
🎯

When to Use

Use custom getters and setters when you want to add extra logic during property access or assignment. For example:

  • Validate data before saving it to a property.
  • Transform data when reading it, like formatting or calculating a value.
  • Log or track changes to a property.
  • Control access to sensitive data.

This helps keep your code clean by centralizing property rules instead of scattering checks everywhere.

Key Points

  • Custom getters run when you read a property.
  • Custom setters run when you assign a value.
  • Use field inside setters/getters to access the actual stored value.
  • They help add validation, transformation, or side effects.
  • Keep property logic in one place for easier maintenance.

Key Takeaways

Custom getters and setters let you control how properties are read and written in Kotlin.
Use the field keyword inside them to access the real stored value.
They are useful for validation, formatting, or adding side effects on property access.
Custom accessors keep your code clean by centralizing property logic.
They run automatically whenever the property is used, so no extra calls are needed.