0
0
KotlinConceptBeginner · 3 min read

What is Delegated Property in Kotlin: Simple Explanation and Example

A delegated property in Kotlin is a property whose getter and setter logic is handled by another object, called a delegate. Instead of writing property code yourself, you let the delegate manage it using the by keyword.
⚙️

How It Works

Imagine you have a friend who is really good at organizing your schedule. Instead of doing it yourself, you ask your friend to handle it for you. In Kotlin, a delegated property works the same way: you let another object take care of the property's behavior.

When you declare a property with by followed by a delegate object, Kotlin automatically calls the delegate's methods to get or set the property's value. This means you don't have to write the usual code for storing or validating the property yourself.

This mechanism helps keep your code clean and reusable, because you can use the same delegate for many properties or classes.

💻

Example

This example shows a simple delegated property that logs every time the property is accessed or changed.

kotlin
import kotlin.reflect.KProperty

class LoggingDelegate {
    private var value: String = ""

    operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
        println("Getting value of '${property.name}': $value")
        return value
    }

    operator fun setValue(thisRef: Any?, property: KProperty<*>, newValue: String) {
        println("Setting value of '${property.name}' to '$newValue'")
        value = newValue
    }
}

class User {
    var name: String by LoggingDelegate()
}

fun main() {
    val user = User()
    user.name = "Alice"
    println(user.name)
}
Output
Setting value of 'name' to 'Alice' Getting value of 'name': Alice Alice
🎯

When to Use

Use delegated properties when you want to reuse common property logic without repeating code. For example, you can delegate to handle lazy loading, observable changes, or storing values in a map.

Real-world uses include:

  • Lazy initialization: load a value only when needed.
  • Observable properties: react when a value changes.
  • Storing properties in a map for dynamic data.

This makes your code simpler, cleaner, and easier to maintain.

Key Points

  • Delegated properties use the by keyword to link a property to a delegate object.
  • The delegate handles getting and setting the property value.
  • This helps avoid repeating code for common property behaviors.
  • Kotlin provides built-in delegates like lazy and observable.

Key Takeaways

Delegated properties let another object manage property behavior using the 'by' keyword.
They simplify code by reusing common property logic like lazy loading or change tracking.
You can create custom delegates by defining getValue and setValue operator functions.
Kotlin includes useful built-in delegates such as lazy and observable for common tasks.