Delegation
Property Delegation
Delegated properties are described on a separate page: Delegated Properties.
Implementation by 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:
1. interface Base {
2. fun print()
3. }
5. class BaseImpl(val x: Int) : Base {
6. override fun print() { print(x) }
7. }
9. class Derived(b: Base) : Base by b
11. fun main() {
12. val b = BaseImpl(10)
13. Derived(b).print()
14. }
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 might expect: the compiler will use your override implementations instead of those in the delegate object. If we were to add override fun printMessage() { print("abc") } to Derived, the program would print “abc” instead of “10” when printMessage is called:
1. interface Base {
2. fun printMessage()
3. fun printMessageLine()
4. }
6. class BaseImpl(val x: Int) : Base {
7. override fun printMessage() { print(x) }
8. override fun printMessageLine() { println(x) }
9. }
11. class Derived(b: Base) : Base by b {
12. override fun printMessage() { print("abc") }
13. }
15. fun main() {
16. val b = BaseImpl(10)
17. Derived(b).printMessage()
18. Derived(b).printMessageLine()
19. }
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:
1. interface Base {
2. val message: String
3. fun print()
4. }
6. class BaseImpl(val x: Int) : Base {
7. override val message = "BaseImpl: x = $x"
8. override fun print() { println(message) }
9. }
11. class Derived(b: Base) : Base by b {
12. // This property is not accessed from b's implementation of `print`
13. override val message = "Message of Derived"
14. }
16. fun main() {
17. val b = BaseImpl(10)
18. val derived = Derived(b)
19. derived.print()
20. println(derived.message)
21. }
