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.
