Kotlin Delegation

Kotlin Delegated Properties

Panduka Wedisinghe
Nerd For Tech
2 min readMay 27, 2021

--

In this article, we will explore what Kotlin delegation is and what are Kotlin delegated properties. To begin with, let’s discuss what delegation means in general.

What is a delegate?

Kotlin delegate is a regular property that shifts the burden of getting and setting (read/write) its value to another function associated with it. Kotlin offers a few different types of delegations.

Kotlin delegated properties

Kotlin provides standard factory methods for several kinds of delegates.

Lazy Initialization

Lazy initialization is important when it is required to initialize a variable or a constant only when it is needed in the code. In the code snippet shown below, by keyword indicates that we will use a delegate to initialize the value of the initByLazy constant. Lazy means that we will run the code inside the block only once if needed. Once the initByLazy is invoked for the first time, Kotlin stashes away the value and uses the stashed value in future references.

But there is a potential issue with the lazy initialization of android views. If a view is stashed away like this, it holds the reference to the context, and this may lead to memory leaks.

Lazy initialization

Observable

The Observable delegate property is handy when required to do something every time the value is changed. If we look at the code snippet given below, initially, the observableData is 0, and the isValueChanged is false.

After assigning a new value to the observableData, the stored value is changed, and the isValueChanged becomes true. Every time the callback function is invoked only after the value is updated.

Kotlin observable

Vetoable

The Vetoable delegate is very much similar to the Observable delegate. The only difference is that the callback should have a condition that should be satisfied to update the variable's value. In the example mentioned below, the new value should be greater than or equal to 0 to update the vetoableData. The callback is invoked only after this condition is met.

Kotlin Vetoable

Lazy initialization, Observable, and Vetoable delegate properties become handy and useful properties when dealing with constantly changing properties in our code. I believe this article helps you to have a good understanding of Kotlin delegate properties.

--

--

Panduka Wedisinghe
Nerd For Tech

Android Developer /Software Engineer/Flutter Developer