Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Kotlin
Stage 5: Specialization

Part 15 / Topic 4 of 6

Delegated properties

val x by delegate and var x by delegate hand reading and writing x off to another object. The delegate just needs operator functions named exactly getValue (and setValue for a var) with a specific signature -- there's no interface to implement, only a naming convention the compiler checks for.

The standard library ships the common delegates ready-made:

class ReportCard {
    val expensiveReport: String by lazy {
        println("  (computing report -- this should print only once)")
        "report-for-march"
    }
}

class Product {
    var cityForDelivery: String by Delegates.observable("Pune") { property, old, new ->
        println("  ${property.name}: $old -> $new")
    }

    var priceInr: Int by Delegates.vetoable(100) { property, old, new ->
        if (new < 0) {
            println("  rejected ${property.name}: $old -> $new")
            false                  // returning false rejects the write entirely
        } else {
            true
        }
    }
}
before first access
  (computing report -- this should print only once)
report-for-march
report-for-march
  cityForDelivery: Pune -> Mumbai
  cityForDelivery: Mumbai -> Chennai
  rejected priceInr: 250 -> -50
final price: 250
  • by lazy { ... } runs the block once, on first read, and caches the result forever -- the second report-for-march print proves the block didn't run again.
  • Delegates.observable(initial) { property, old, new -> ... } runs its callback after every write, with the property's own name available through property.name.
  • Delegates.vetoable(initial) { ... } runs its callback before the write and can reject it by returning false -- the priceInr = -50 attempt in the full example never takes effect, and priceInr stays at 250.

A Map can even back a set of read-only properties directly -- useful for simple config parsed from JSON or similar, where each property reads the entry matching its own name:

val config: Map<String, Any?> = mapOf("customerName" to "Asha Verma", "age" to 29)
val customerName: String by config
val age: Int by config
Asha Verma is 29 years old

A plain by map throws NoSuchElementException if the key is missing; by map.withDefault { "fallback" } supplies one instead of throwing.

What by actually compiles to

Part 15's mini-build (section 6) writes a delegate from scratch, and javap on the resulting class shows exactly what the by keyword expands to -- a hidden xxx$delegate field per delegated property, a shared $$delegatedProperties array of KProperty instances (so the delegate gets told which property called it, without doing reflection on every access), and every read/write turned into a plain method call on the delegate:

public final class Order {
  static final kotlin.reflect.KProperty<java.lang.Object>[] $$delegatedProperties;
  private final Logged status$delegate;
  private final Logged courierPartner$delegate;
  ...
  public final java.lang.String getStatus();
  public final void setStatus(java.lang.String);
}
public final java.lang.String getStatus();
    Code:
       0: aload_0
       1: getfield      #61    // Field status$delegate:LLogged;
       4: aload_0
       5: getstatic     #80    // Field $$delegatedProperties:[Lkotlin/reflect/KProperty;
       8: iconst_0
       9: aaload
      10: invokevirtual #84    // Method Logged.getValue:(Ljava/lang/Object;Lkotlin/reflect/KProperty;)Ljava/lang/Object;

getStatus() is nothing but status$delegate.getValue(this, $$delegatedProperties[0]). by lazy, Delegates.observable, and your own delegate are all the exact same mechanism -- lazy { } just returns a ready-made object with a getValue that caches.

Full program: examples/04_delegated_properties.kt.

Done here? The practice set for Part 15 — including the solutions — is on the part page.

Search the guide