liveBook · Manning

Class delegation

As explained in Kotlin in Action, 2E

Class delegation is a Kotlin language feature that generates interface-member implementations by forwarding them to a specified delegate object.

Class delegation uses Kotlin’s by keyword to forward interface implementations to another object. It replaces repetitive decorator methods while avoiding fragile implementation inheritance. section 4.3.3

class DelegatingCollection<T>(
   innerList: Collection<T> = mutableListOf<T>()
) : Collection<T> by innerList

A Collection implementation can delegate every interface member to innerList, leaving the class body empty. section 4.3.3

Use delegation when a class should expose an interface while reusing another object’s behavior:

  • Declare the interface followed by by and the delegate expression. section 4.3.3
  • Override only the members whose behavior needs modification; delegated members remain generated by the compiler. section 4.3.3
  • Prefer this approach over manually forwarding many methods, especially when adding behavior to a class that was not designed for inheritance. section 4.3.3

Counting additions while delegating collection behavior

CountingSet<T> delegates MutableCollection<T> to innerSet, then overrides add and addAll to count supplied objects. Calling addAll(listOf(1, 1, 2)) reports three additions and two unique elements, showing that custom behavior can surround delegated operations.

How Kotlin in Action, 2E covers it

How deep it goes
Explains the by syntax, compiler-generated forwarding, decorator motivation, and selective overrides, but not generated bytecode internals.
Examples
Demonstrates delegated Collection and MutableCollection implementations, including a CountingSet that overrides addition methods.
What it assumes
Assumes familiarity with Kotlin classes and interfaces while reinforcing final-by-default classes and the risks of implementation inheritance.
What you can do after
Apply it via Kotlin’s by keyword to compose interface behavior and override only the operations requiring customization.
How it connects
Connects class delegation with interfaces, decorator pattern, implementation inheritance, and Java-style inheritance conventions.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kotlin in Action, 2E. The section links point to the parts of the book it draws on.