Caveats of Kotlin Delegation
Explore the practical implications and caveats of Kotlin delegation in this lesson. Understand how delegation differs from inheritance, why a delegating class may be assigned to an interface type, and challenges when delegating to mutable properties. Gain insight into Kotlin's implementation details and how they influence object lifetime management. This knowledge helps you safely implement delegation for adaptable design and robust code reuse.
We'll cover the following...
Implementation caveat
In the example we’ve created so far, the Manager may delegate calls to an instance of a JavaProgrammer, but a reference to a Manager may not be assigned to a reference of a JavaProgrammer—that is, a Manager may use a JavaProgrammer, but a Manager may not be used as a JavaProgrammer. In other words, a Manager has a JavaProgrammer but is not a kind of JavaProgrammer. Thus, delegation offers reuse without accidentally leading to substitutability as inheritance does.
However, there’s one small consequence of how Kotlin implements delegation. The delegating class implements the delegating interface, so a reference to the delegating class may be assigned to a reference of the delegating interface. Likewise, a reference to a delegating class may be passed to methods that expect a delegate ...