Under the hood of Kotlin Class Delegation
A piece of rather popular advice heard in software development is “favour composition over inheritance”. I won’t go into the details of why as there is an excellent chapter in “Effective Java” about it, as well as this nice article by Eric Lin.
This article explores how class delegation can be useful and how it works under the hood.
In our case, we had a custom view which should expose an interface looking like this:
Now it was time to create the
Of course, we don’t want to start putting logic into our view just for the sake of exposing the interface through it, which meant that the view now had to act as a “proxy” (implementing the interface and calling the
Not a nice solution, but at least we extracted the logic. The view was still cluttered though :(
Class Delegation to the rescue
by keyword in Kotlin, properties and even classes can be delegated. You might know it from using
You can also delegate inheritance, which is what we are after. The usage looks like this:
This delegates the methods from
ArtboardCanvas . No more cluttering with “proxy” calls!
Under The Hood
Under the hood, Kotlin actually doesn’t do any “black magic”: It just generates a function which invokes the delegate. The bytecode, decompiled to Java looks like this:
If you have a lot of methods, that code will still be generated and adding to your compiled code’s size, but at least it doesn’t clutter your code anymore!
If you are encountering a scenario where you want to expose an API through a class, especially if you have multiple interfaces, class delegation can help you keep your code clean while still extracting the logic.