Delegation in Kotlin
Delegation is a way to reuse behaviour without inheriting. Instead of class B : A() you write class B(p: I) : I by p: B implements interface I, but every method of it forwards to the object p. The forwarding methods are written for you by the compiler, so this is composition over inheritance — the preferred way to reuse code without a fragile class hierarchy.
The simplicity is deceptive, and interviews probe exactly the corners. The by keyword is not inheritance and not by lazy (property delegation is a separate mechanism). An explicit override in the class always wins over the delegate. And the delegate itself calls its own methods and does not see the derived class's overrides — this is the "self problem", a source of silent bugs. The full map lives in the layer below.
Topic map
- Interface delegation with by — how
byforwards methods to an object, why it is composition, override precedence, and the self problem.
Common traps
| Mistake | Consequence |
|---|---|
Reading by as inheritance | A wrong model — by forwards methods, it does not build a hierarchy |
Confusing interface delegation with by lazy | These are different mechanisms of one keyword |
Thinking the delegate p is copied | It is held by reference — state shared with the outer owner |
Assuming the delegate's method overrides an explicit override | The opposite — the class's override always wins |
Expecting the delegate to see the derived class's override | The delegate calls its own methods — it does not see the class's overrides |
| Delegating one interface to two objects | A shared-method conflict — the class must override it explicitly |
Interview relevance
The topic is asked to check whether you separate composition from inheritance and understand that a delegate is a separate object with its own this. A candidate who says "by generates forwarding methods, but an explicit override shadows them, and the delegate calls its own methods without seeing mine" gets ahead of "by is like extends".
Typical checks:
- What
bydoes — forwarding every interface method to a held object. - That it is composition over inheritance and why it is often preferred.
- The precedence — an explicit class
overridewins over the delegate. - The self problem — the delegate does not see the derived class's overrides.
Common wrong answer: "by makes B a subclass of p and inherits its fields" or "the delegate always beats override". In fact by forwards calls to an object held by reference, and an override in the class itself is always stronger than the delegate.