0
0
Kotlinprogramming~3 mins

Why Custom delegated properties in Kotlin? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could add smart behavior to variables with just one line of code?

The Scenario

Imagine you have many variables in your Kotlin program that need special behavior when getting or setting their values, like logging changes or validating input. Doing this manually for each variable means writing repetitive code everywhere.

The Problem

Manually adding the same code to handle getting and setting for each variable is slow and error-prone. It clutters your code, making it hard to read and maintain. If you want to change the behavior, you must update every variable separately.

The Solution

Custom delegated properties let you write the special get/set logic once in a delegate class. Then, you simply tell variables to use that delegate. This keeps your code clean, reusable, and easy to update.

Before vs After
Before
var name: String = ""
get() {
    println("Getting name")
    return field
}
set(value) {
    println("Setting name to $value")
    field = value
}
After
import kotlin.reflect.KProperty

class LoggerDelegate {
    private var value: String = ""
    operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
        println("Getting ${property.name}")
        return value
    }
    operator fun setValue(thisRef: Any?, property: KProperty<*>, newValue: String) {
        println("Setting ${property.name} to $newValue")
        value = newValue
    }
}

var name: String by LoggerDelegate()
What It Enables

You can add custom behavior to variables easily and reuse it everywhere without repeating code.

Real Life Example

In an app, you might want to log every time a user setting changes. Using custom delegated properties, you write the logging once and apply it to all settings variables effortlessly.

Key Takeaways

Manual get/set code is repetitive and hard to maintain.

Custom delegated properties let you write special behavior once.

They make your code cleaner, reusable, and easier to update.