Basics

First things first, what is a delegate and how does it work? Well, while it may seem like some kind of magic, it’s really not that complicated.

A delegate is just a class that provides the value for a property and handles its changes. This allows us to move, or delegate, the getter-setter logic from the property itself to a separate class, letting us reuse this logic.

Let’s say we want a String property param that always has a trimmed string, i.e. with leading and trailing whitespace removed. We could do this in the property's setter like this:

If you’re confused about the syntax, please refer to the Properties page in the Kotlin docs.

Now, what if we want to reuse this functionality in some other class? Here’s where delegates come in to play:

So a delegate is just a class with two methods: for getting and setting value of a property. To give it some more information, it is provided with the property it’s working with via the instance of KProperty class, and an object that has this property via thisRef . That's it! And here is how we can use this newly created delegate:

which is equivalent to this:

::param is an operator that returns an instance of KProperty class for the property.

As you can see, there is nothing mysterious about delegates. But despite their simplicity, they can be very useful. So let’s look at some examples, specific to Android.

You can read more about delegates in the official docs.