Under the hood of Kotlin Class Delegation

Jossi Wolf
Snapp Mobile
Published in
2 min readApr 9, 2019
I was told to add an image to the post, so here’s one Photo by Jf Brou from Unsplash. Bonus points since Samoyeds are some of the cutest dogs out there!

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 CanvasCapabilities implementation.

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 ArtboardCanvas ):

Not a nice solution, but at least we extracted the logic. The view was still cluttered though :(

Class Delegation to the rescue

Using the by keyword in Kotlin, properties and even classes can be delegated. You might know it from using lazy :

You can also delegate inheritance, which is what we are after. The usage looks like this:

This delegates the methods from CanvasCapabilities to 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!

Conclusion

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.

Thanks to Juhani Lehtimäki and Daniel Hartwich for reviewing!

--

--

Jossi Wolf
Snapp Mobile

Software Engineer @Google working on Jetpack Compose. I like Kotlin, Animations and Rabbits! speakerdeck.com/jossiwolf