Zero boilerplate delegation in Kotlin

Zero boilerplate delegation in Kotlin

Piotr Ślesarew

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 worst than no abstraction.

Words are cheap, let’s code a little bit.

class CopyPrinter implements Copy, Print {

    private Copy copier;
    private Print printer;

    public CopyPrinter(Copy copier, Print printer) {
        this.copier = copier;
        this.printer = printer;
    }

    @Override
    public Page copy(Page page) {
        return copier.copy(page);
    }

    @Override
    public void print(Page page) {
        printer.print(page);
    }
}

interface Copy {
    Page copy(Page page);
}

interface Print {
    void print(Page page);
}

class Page {}

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 delegationpattern implemented in language. Guess what! Kotlin has it❤.

class CopyPrinter(copier: Copy, printer: Print) : Copy by copier, Print by printer

interface Copy {
    fun copy(page: Page): Page
}

interface Print {
    fun print(page: Page)
}

class Page

Just amazing. When I saw it for the first time it literally blew my mind. Kotlin makes it so clear and concise that I do not have to explain what the code does.

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

Any piece of code that you’re forced to duplicate or that can be automatically generated by an IDE is a missing language abstraction feature. — (Mario Fusco)

Notes:

GoF, Delegated Properties, Kotlin, Henry Lieberman