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:
onChangetakes a callback instead of printing directly, soLoggeditself stays generic --Orderdecides that "logged" means "append to a sharedtraillist," somethingDelegates.observablecan't do (its callback has no shared state to write into unless you close over one yourself, which is exactly what's happening here).statusandcourierPartnereach get their ownLoggedinstance but share the sametraillist, because the lambda passed to each one closes overOrder's owntrailproperty -- that's why the printed trail interleaves both properties in the order they changed. This is the exact behaviorjavapconfirmed in section 4: two separatexxx$delegatefields, reading and writing from each independently.- Setting
status = "SHIPPED"twice in a row logs only once, becausesetValuecomparesnewValue != valuebefore callingonChangeat all -- a detailDelegates.observabledoes 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.