Delegation is an implementation mechanism in which an object forwards or delegates a request to another object. — (GoF)

It is said that inheritance is useful only in case of having Donald Trump as a father. Abstract classes have a lot of gotchas in term of designing scalable and reusable architecture. How many times did you create the superclass in your codebase that could not be replaced and blocked you from doing new fancy features? Thanks to Henry Lieberman our programming toolbox include an amazing delegation, so it can be used against wrong abstractions. Remember! The wrong abstraction is worse than no abstraction.

Words are cheap, let’s compose a CopyPrinter class.

The sample above is pretty straightforward, but still begging for some code generation because of having boilerplate in it. It would be so nice to have delegation as a built-in language feature. In old Java world things like that does not exist, so is there any way to solve that problem differently? It is possible to use annotation processing to create a library for code generation or implement reflection to invoke methods dynamically. That sounds pretty scary, right? As a fan of Kotlin, I will show you how to delegate like a pro.

Kotlin

As I have already mentioned, there is a huge need of having delegation pattern implemented in language. Guess what! Kotlin has it❤.

Kotlin delegation mechanism squashes 30 lines of Java code in just 11. When I saw it for the first time it literally blew my mind. Kotlin makes it so clear and concise that there is no need for explanation. However, nothing is for free and there is no magic behind it. As an engineer, I always dig deeper to fully feed my appetite and see how things work internally.

The easiest way to understand how Delegates work is by using IntelliJ IDEA.

IntelliJ IDEA comes with bundled Kotlin decompiler so you can explore generated bytecode and translate it to Java. By doing it on our sample you are able to see such a beauty.

I intentionally deleted imports and metadata to improve readability, so now it can be seen that everything is generated and no dark magic is involved in Delegates.

And if that is not enough, Kotlin have the whole concept of Delegated Properties. If you are not familiar with it, you should read about it and start using as soon as possible.