Getter and Setter in Kotlin: What They Are and How They Work
getter and setter are special functions that control how you read and write the value of a property. They let you customize what happens when you get or set a variable, like adding checks or changing the value behind the scenes.How It Works
Think of a property in Kotlin like a box that holds a value. The getter is like the lid you open to see what's inside, and the setter is like the way you put something new into the box. By default, Kotlin gives you simple lids and openings that just show or change the value directly.
But sometimes, you want to do more when someone looks inside or changes the box. Maybe you want to check if the new value is okay before accepting it, or maybe you want to change the value before giving it out. That's when you write your own getter and setter. They act like custom rules for reading and writing the property.
Example
This example shows a property with a custom getter and setter. The setter checks if the new value is positive before saving it, and the getter returns the stored value.
class BankAccount { var balance: Int = 0 get() = field set(value) { if (value >= 0) { field = value } else { println("Balance cannot be negative") } } } fun main() { val account = BankAccount() account.balance = 100 println(account.balance) // Prints 100 account.balance = -50 // Prints warning, value not changed println(account.balance) // Still prints 100 }
When to Use
Use getter and setter when you want to control how a property is accessed or changed. For example, you might want to:
- Validate data before saving it, like checking for negative numbers.
- Calculate a value on the fly instead of storing it.
- Log or track when a property changes.
- Hide the real data and show a modified version.
This helps keep your code safe and clear, especially in bigger projects where data rules matter.
Key Points
- Getters and setters let you customize property access in Kotlin.
- By default, Kotlin provides simple getters and setters.
- You write custom ones to add checks, calculations, or side effects.
- Use
fieldinside setters/getters to refer to the actual stored value.
Key Takeaways
field keyword inside setters/getters to access the real property value.