One of the patterns that is super integrated in Kotlin is the delegation pattern. It helps the developer to reuse code easily and keep the readability of the language elegant and simple.
If you’ve been writing Kotlin code for some time, you’ve probably seen the
by lazy expression.
The lazy delegate provides a setter and a getter, but in this case, it works so that the variable is only computed once. After that, the value is only passed around when readed, because the computed value is maintained in memory.
At the end of the day, what this delegate is doing is giving the responsibility of providing a getter and a setter to another class, using the keyword
Implementing a custom delegate
My favorite use case for custom delegates comes when working with LiveData. The idea is that the content store in the
LiveData object could be accessed without using the value variable to read or write its content.
Normally, we would have something like this.
MutableLiveData is hidden so that it can only be accessed from the
ViewModel, and the
LiveDataobject is exposed. Each time we need to modify its content we need to use the variable with the underscore (which in my opinion looks ugly), and then read or write over the value property.
We are going to use delegates to avoid this. To start, we need a class that is going to take the responsibility we talk about before, this is the one to which we are going to delegate the getter and setter.
In this class, we need to override the operators
setValue, so that they write or read the value contained in the
And now using the class that we’ve created before, we can use it to delegate the getter and setter of the
LiveData object, and access it in a cleaner way, like in the following example.
It may seem like a small change, but once you’ve written this code thousands of times, you start to appreciate it.
I also have an article where I talk about Kotlin reified and the inline keyword, in case you are interested in the topic. You can find it here.
If you use
map objects, you can populate a class with them in a more semantic way using delegates, instead of using custom solutions like, for example, loops.
For that, you need to define class like so.
The technology is still new and evolving. There are some projects to share also the UI code using Compose, but this is something that I’ve not tried out, and I don’t want to dive into it.
And then, when you are populating the class, the keys must have the same value as the name of the class property, like this.
If you want to read more content like this without ads and support me, don’t forget to check my profile, or give Medium a chance by becoming a member to access unlimited stories from me and other writers. It’s only $5 a month and if you use this link I get a small commission.