...

/

Caveats of Kotlin Delegation

Caveats of Kotlin Delegation

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 ...