Custom Getter and Setter in Kotlin: What They Are and How to Use
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.
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 }
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
fieldinside 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
field keyword inside them to access the real stored value.