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

Part 15 / Topic 6 of 6

Mini-build: a custom "logged" property delegate

Delegates.observable (section 4) already logs every write -- the point of building one by hand is seeing that there was never anything more to it than two correctly-named functions.

class Logged<T>(initial: T, private val onChange: (name: String, old: T, new: T) -> Unit) {
    private var value: T = initial

    operator fun getValue(thisRef: Any?, property: KProperty<*>): T = value

    operator fun setValue(thisRef: Any?, property: KProperty<*>, newValue: T) {
        if (newValue != value) {               // skip the log line when nothing actually changed
            onChange(property.name, value, newValue)
            value = newValue
        }
    }
}

class Order(val id: String) {
    private val trail = mutableListOf<String>()

    var status: String by Logged("PLACED") { name, old, new -> trail += "$name: $old -> $new" }
    var courierPartner: String by Logged("unassigned") { name, old, new -> trail += "$name: $old -> $new" }

    fun auditTrail(): List<String> = trail.toList()
}
Order ORD-5001 is now DELIVERED, via Delhivery
Audit trail:
  status: PLACED -> PACKED
  courierPartner: unassigned -> Delhivery
  status: PACKED -> SHIPPED
  status: SHIPPED -> DELIVERED

Three design choices worth noticing:

  • onChange takes a callback instead of printing directly, so Logged itself stays generic -- Order decides that "logged" means "append to a shared trail list," something Delegates.observable can't do (its callback has no shared state to write into unless you close over one yourself, which is exactly what's happening here).
  • status and courierPartner each get their own Logged instance but share the same trail list, because the lambda passed to each one closes over Order's own trail property -- that's why the printed trail interleaves both properties in the order they changed. This is the exact behavior javap confirmed in section 4: two separate xxx$delegate fields, reading and writing from each independently.
  • Setting status = "SHIPPED" twice in a row logs only once, because setValue compares newValue != value before calling onChange at all -- a detail Delegates.observable does not give you for free (it fires on every assignment, equal value or not).

Full program: examples/06_mini_build_logged_delegate.kt.

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

Search the guide