Caveats of Kotlin Delegation
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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access