Delegation - by lazy, observable and Class Delegation

Article · 2:00

Handing an implementation to another object, and the three delegates you will actually use.

Property delegation moves the implementation of a property's getter and setter into a separate object, behind the by keyword. Kotlin ships three delegates that cover most needs.

lazy computes the value on first access and caches it. It is the right tool for anything expensive to create that might not be needed, and it is thread-safe by default. observable fires a callback on every change, which is useful for logging or for invalidating a cache. Delegates.notNull allows a non-nullable property to be assigned after construction, throwing if read before.

A map can also be a delegate, so a class can be backed by a key-value store with no manual plumbing - useful when parsing JSON into a loosely-typed object.

Class delegation is the other half. Writing class Foo(b: Bar) : Bar by b implements the Bar interface by forwarding every method to b, with no hand-written forwarding code. This gives you composition with the convenience of inheritance, and it is the idiomatic answer to the decorator pattern. You can override any single method while the rest forward automatically.

import kotlin.properties.Delegates

class Config {
    // Computed once, on first access, then cached
    val settings: Map<String, String> by lazy {
        println("...loading settings now")
        mapOf("theme" to "dark")
    }

    // A callback on every assignment
    var retries: Int by Delegates.observable(0) { _, old, new ->
        println("retries changed from $old to $new")
    }
}

interface Logger {
    fun log(message: String)
}

class ConsoleLogger : Logger {
    override fun log(message: String) = println("LOG: $message")
}

// Every Logger method forwards to delegate, except the one we override
class TimestampLogger(private val delegate: Logger) : Logger by delegate {
    override fun log(message: String) = delegate.log("[12:00] $message")
}

fun main() {
    val config = Config()
    println("created, nothing loaded yet")
    println(config.settings)        // triggers the lazy block
    println(config.settings)        // cached, no second load

    config.retries = 3

    TimestampLogger(ConsoleLogger()).log("started")
}

Discussion

No questions on this topic yet. Sign in to ask the first one.