The Analogy: The Solicitor's Power of Attorney
A busy solicitor's practice runs on delegation. A senior partner holds a client relationship, which carries a fixed set of duties -- file documents, answer correspondence, attend hearings. Rather than perform every duty personally, the partner grants a power of attorney to a capable clerk, authorising the clerk to act for the client on those matters. To the outside world the client's obligations are fully met; behind the desk it is the clerk who actually does the work. The partner has kept the client's interface intact while handing the labour to someone else. This is Kotlin's class delegation: a class satisfies an interface not by writing every method itself, but by naming a delegate that already implements it, with the compiler forwarding each call automatically.
The forwarding is complete and effortless. The partner does not re-draft a description of every duty; the single power-of-attorney instrument forwards the entire mandate to the clerk in one clause. But the partner may reserve specific matters -- perhaps all urgent letters must cross the partner's own desk. Those reserved matters take precedence over the general delegation. In Kotlin, class Managed(base: Contract) : Contract by base forwards the whole Contract to base, and any member the wrapping class chooses to override intercepts just that one call while everything else still flows to the delegate.
The office delegates in a second, finer-grained way as well. A particular client account is not held as loose cash in a drawer; every deposit and withdrawal is mediated by an escrow agent who follows a strict procedure on each transaction. You never touch the balance directly -- you ask the agent, and the agent performs the read or the write. This is a delegated property: the get and set of a single property are handed to a helper object that implements the operations. Some agents are specialised: a lazy escrow fetches the asset only the first time it is requested and then holds it for reuse; an observing agent records a note every time the value changes. The property looks ordinary at the call site, but a delegate stands behind it.
The failure that embarrasses the practice is subtle. The partner reserves urgent letters to handle personally, confident that every urgent letter now gets special treatment. But when the clerk runs a routine that internally decides to "send a letter," the clerk uses their own hand, not the partner's reserved urgent process -- because the clerk's internal call never routes back through the partner who delegated to them. The reservation only intercepts calls made from outside; the delegate's own self-calls bypass it entirely. In Kotlin this is the central subtlety of delegation: an override in the wrapper is invisible to the delegate's internal method calls, so overriding a delegated member does not change how the delegate calls that member on itself.
Syntax or Core Structure
Class delegation uses by on the supertype list: the class implements an interface by forwarding to a delegate instance. The compiler generates the forwarding methods.
interface Filer {
fun file(doc: String): String
fun count(): Int
}
class BasicFiler : Filer {
private var filed = 0
override fun file(doc: String): String { filed += 1; return "filed " + doc }
override fun count(): Int = filed
}
class AuditedFiler(private val inner: Filer) : Filer by inner {
override fun file(doc: String): String = "[audit] " + inner.file(doc)
}
fun main() {
val f: Filer = AuditedFiler(BasicFiler())
println(f.file("deed"))
println(f.file("will"))
println("count " + f.count())
}
Output:
[audit] filed deed
[audit] filed will
count 2
AuditedFiler declares : Filer by inner, so every Filer method it does not override is forwarded to inner automatically -- count() is not written in AuditedFiler at all, yet it works by delegating to BasicFiler. The one member AuditedFiler overrides, file, wraps the delegate's result with an "[audit]" prefix and still calls inner.file to do the real work, which bumps inner's counter. After filing two documents, count() forwards to the delegate and reports 2. This is composition with almost no boilerplate: reuse an implementation, override only what you must.
Technical Depth: Delegated Properties
The standard property delegates
A property can hand its get and set to a delegate object after the by keyword. The standard library ships several, each an escrow agent with a different procedure.
| Delegate | For | Behaviour |
|---|---|---|
by lazy { } | val | computes once on first read, then caches |
by Delegates.observable(init) { } | var | runs a callback after each change |
by Delegates.vetoable(init) { } | var | can reject a proposed change |
by Delegates.notNull() | var | throws if read before assignment |
by map | val/var | reads/writes a backing Map entry |
Each delegate implements getValue (and setValue for a var), so the property at the call site looks completely ordinary while the delegate does the work behind it.
Lazy computes once
by lazy defers an expensive initializer until the first read and remembers the result.
class Report {
val header: String by lazy {
println("computing header")
"ANNUAL REPORT"
}
}
fun main() {
val r = Report()
println("before first read")
println(r.header)
println(r.header)
}
Output:
before first read
computing header
ANNUAL REPORT
ANNUAL REPORT
The lazy initializer does not run at construction: "before first read" prints while header is still uncomputed. The first r.header triggers the block, so "computing header" prints once and the value "ANNUAL REPORT" is returned and cached. The second r.header returns the cached value without re-running the block, which is why "computing header" appears exactly once.
A custom delegate implements getValue and setValue
You can write your own delegate by providing getValue and setValue operator functions. Here a delegate trims and records writes.
import kotlin.reflect.KProperty
class Trimmed {
private var stored: String = ""
operator fun getValue(ref: Any?, prop: KProperty<*>): String = stored
operator fun setValue(ref: Any?, prop: KProperty<*>, value: String) {
stored = value.trim()
}
}
class Form {
var name: String by Trimmed()
}
fun main() {
val form = Form()
form.name = " Ada "
println("[" + form.name + "]")
}
Output:
[Ada]
Assigning " Ada " to form.name routes through the delegate's setValue, which trims the whitespace before storing "Ada". Reading form.name routes through getValue, returning the stored value. The square brackets in the print make the trimming visible: the output is "[Ada]" with no surrounding spaces. The property syntax is unchanged; a delegate intercepted every access.
Backing properties by a map
A Map can serve as the delegate for several properties at once: each property reads the map entry whose key matches its own name. This is handy for turning loosely-typed configuration into typed properties.
class Settings(source: Map<String, Any?>) {
val theme: String by source
val fontSize: Int by source
}
fun main() {
val s = Settings(mapOf("theme" to "dark", "fontSize" to 14))
println(s.theme)
println("size " + s.fontSize)
}
Output:
dark
size 14
Each property delegates to source, looking itself up by name: theme reads the "theme" entry and fontSize reads the "fontSize" entry, casting each to its declared type. The output shows "dark" and "size 14". The catch to keep in mind is that a missing key or a wrong type surfaces only at read time as an exception, so map-backed properties trade compile-time safety for flexibility.
Real World Example: Wrapping a Notifier
A team has a working BasicNotifier and wants a variant that marks every message urgent. Delegation looks perfect: wrap the basic notifier, forward everything with by, and override just send to add an "[urgent]" prefix. The interface also has a bulk sendAll, which the basic implementation writes in terms of send.
interface Notifier {
fun send(msg: String): String
fun sendAll(msgs: List<String>): List<String>
}
class BasicNotifier : Notifier {
override fun send(msg: String): String = "sent: " + msg
override fun sendAll(msgs: List<String>): List<String> =
msgs.map { send(it) } // internal self-call to send
}
class PrefixNotifier(private val inner: Notifier) : Notifier by inner {
override fun send(msg: String): String = inner.send("[urgent] " + msg)
}
fun main() {
val n: Notifier = PrefixNotifier(BasicNotifier())
println(n.send("fire"))
println(n.sendAll(listOf("flood", "quake")))
}
Output:
sent: [urgent] fire
[sent: flood, sent: quake]
The single-message path works as intended. n.send("fire") calls PrefixNotifier.send, which prepends "[urgent] " and forwards to the delegate, producing "sent: [urgent] fire". The wrapper reused the delegate's real sending logic and added exactly one behaviour on top, with almost no code.
The bulk path betrays the expectation. sendAll is not overridden in PrefixNotifier, so it is forwarded wholesale to BasicNotifier.sendAll. That method calls send(it) -- but "self" there is the BasicNotifier instance, not the PrefixNotifier wrapping it, so it invokes BasicNotifier.send directly. The "[urgent]" prefix never appears, and the batch comes out as "[sent: flood, sent: quake]". Two code paths that a reader assumes are consistent produce different results.
This is the genuine design flaw, and it is inherent to delegation rather than a typo. An override in the wrapper intercepts only calls made from outside; the delegate's internal self-calls route to the delegate's own methods and cannot see the override. Inheritance would behave differently -- a subclass's overridden send would be reached by virtual dispatch even from an inherited sendAll -- which is exactly the trade delegation makes: looser coupling at the cost of no virtual link back into the wrapper. The fix here is to override sendAll in PrefixNotifier too, implementing it as msgs.map { send(it) } so it routes through the wrapper's own send; or, if every internal call must be intercepted, to use an open base class and inheritance instead of delegation. The limitation to remember is that by gives you forwarding, not overriding of the delegate's internals.
Common Mistakes
- Expecting the delegate's self-calls to hit your override. Class delegation forwards external calls only; when the delegate calls its own method internally, it uses its own implementation, not your override. Override every member whose internal use matters, or use inheritance.
- Keeping a duplicate copy of state in the wrapper. If the wrapper caches a value the delegate also holds, the two drift apart. Let the delegate own the state and forward reads to it.
- Assuming
by lazyre-evaluates. A lazyvalcomputes once and caches forever; it never recomputes even if inputs change. Use a plain getter or a function when the value must stay live.
- Reading a
Delegates.notNull()orlateinitproperty before assignment. Both throw at read time if unset. Assign before first read, and prefer a nullable or default when "unset" is a legitimate state.
- Confusing
lateinitwith a delegated property.lateinit varis a distinct mechanism with no delegate object and only works for non-nullvars of non-primitive type; it is notbyanything.
- Forgetting that
by lazyis thread-safe by default. The defaultLazyThreadSafetyMode.SYNCHRONIZEDadds locking; if a property is confined to one thread,lazy(LazyThreadSafetyMode.NONE)is cheaper, but do not use it across threads.
- Writing a custom delegate with the wrong operator signature.
getValue/setValuemust take the receiver and aKProperty<*>; a mismatched signature fails to resolve and thebywill not compile.
- Delegating to a mutable object shared elsewhere. If the delegate instance is also referenced outside the wrapper, external mutation changes the wrapper's behaviour. Own the delegate exclusively unless sharing is intended.
- Reaching for delegation when inheritance is the real relationship. Delegation models "has-a and forwards to"; if you truly need virtual dispatch through inherited methods, an
openbase class is the correct tool.
Best Practices
- Use class delegation to compose behaviour from an existing implementation, overriding only the members you need to change.
- Remember that overrides in a delegating wrapper do not intercept the delegate's internal self-calls; override those members too when their internal use matters.
- Let the delegate own its state and forward to it, rather than mirroring state in the wrapper where it can drift.
- Reach for
by lazyfor expensive values read at most once per lifetime, and choose the thread-safety mode deliberately. - Use
Delegates.observableandvetoablefor change notification and validation instead of hand-writing setters. - Back configuration-style properties with
by mapwhen the data naturally arrives as a map, keeping the property surface typed and clean. - Keep custom delegates small and single-purpose, with correct
getValue/setValuesignatures, so they read as ordinary properties at the call site. - Prefer an
openbase class over delegation only when you genuinely need virtual dispatch through the type's own internal calls.
Practice Exercises
- Implement a
Loggerinterface in aConsoleLogger, then aCountingLogger(inner: Logger) : Logger by innerthat overrides only the log method to also increment a counter, forwarding everything else. Confirm the forwarded members work without being written.
- Add a
val config: String by lazy { }to a class whose initializer prints a line. Read it twice and confirm the initializer runs exactly once.
- Reproduce the self-call flaw: give an interface a method implemented in terms of another, wrap it with delegation overriding only the inner method, and observe that the bulk method ignores your override. Then fix it by overriding the bulk method too.
- Write a custom delegate that clamps an
Intproperty into the range 0 to 100 on assignment viasetValue. Assign values below, inside, and above the range and confirm the stored value is clamped.