Delegation
The Delegation pattern has proven to be a good alternative to implementation inheritance, and Kotlin supports it natively requiring zero boilerplate code.
A class Derived
can implement an interface Base
by delegating all of its public members to a specified object:
The by
-clause in the supertype list for Derived
indicates that b
will be stored internally in objects of Derived
and the compiler will generate all the methods of Base
that forward to b
.
Overriding a member of an interface implemented by delegation
Overrides work as you expect: the compiler will use your override
implementations instead of those in the delegate object. If you want to add override fun printMessage() { print("abc") }
to Derived
, the program would print abc instead of 10 when printMessage
is called:
Note, however, that members overridden in this way do not get called from the members of the delegate object, which can only access its own implementations of the interface members:
Learn more about delegated properties.