0
0
Kotlinprogramming~3 mins

Why Custom getters and setters in Kotlin? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could control property changes automatically without extra functions everywhere?

The Scenario

Imagine you have a class with a property, and you want to control how its value is read or changed. Without custom getters and setters, you have to write extra functions everywhere to check or modify the value manually.

The Problem

This manual approach is slow and easy to forget. You might miss checks or updates, causing bugs. It also clutters your code with repetitive functions, making it hard to read and maintain.

The Solution

Custom getters and setters let you define special code that runs automatically when you get or set a property. This keeps your checks and updates in one place, making your code cleaner and safer.

Before vs After
Before
private var age: Int = 0
fun setAge(value: Int) { if (value >= 0) age = value }
fun getAge(): Int { return age }
After
var age: Int = 0
  set(value) { if (value >= 0) field = value }
  get() = field
What It Enables

You can easily add rules and logic to property access, making your code more reliable and easier to understand.

Real Life Example

For example, in a banking app, you can prevent setting a negative balance by adding a custom setter that blocks invalid values automatically.

Key Takeaways

Manual property control is repetitive and error-prone.

Custom getters and setters centralize logic for cleaner code.

This makes your programs safer and easier to maintain.