Kotlin Standard Delegates — Lazy, Observable and Vetoable

Photo by Marc-Olivier Jodoin on Unsplash

Delegation is an object-oriented design pattern and Kotlin supports it’s natively. If you are not familiar with the native support of delegation by Kotlin read this.

Kotlin standard library has some predefined set of delegates that can be used.

Lazy Delegate

Suppose you have a property that is computationally expensive to instantiate and might not be ever needed or just for a single instance is needed. In this scenario lazy delegate is beneficial. The lazy delegate allows the value of a property to be computed only on first access and then cached.

By default, the evaluation of lazy properties is synchronized: the value is computed only in one thread, but all threads will see the same value.

Observable Delegate

Suppose a scenario where you want to observe every change in the value of the parameter the old value and the new value. The handler is called every time you assign to the property (after the assignment has been performed). The observable delegate allows for a lambda to be triggered any time the value of the property changes.

Vetoable Delegate

Suppose a scenario, where you want to intercept the assignment of a variable value. Like you have the condition until and unless it is satisfied the value of the field will not get changed.

Other Delegate

As of Kotlin 1.4, it is also possible to delegate directly to another property. For example, if we are renaming a property in an API class, we may leave the old one in place and simply delegate it to the new one. To delegate property to another property, use the :: the qualifier in the delegate name, for example, this::delegate or MyClass::delegate.

Some Reference

For any doubts and suggestions, you can reach out on my Instagram, LinkedIn. Follow me for Kotlin content and more. Happy Coding!

I will well appreciate one of these 👏

Recent Posts:




We are here building a community here.

Recommended from Medium

Kotlin DSL for Dummies

Mobile topics 1

DiffUtil — A smarter way to update items in RecyclerView

Testing in Android a Zero to Hero Tutorial-Part 3

Need a Hands-Free Android Experience? Turn On Voice Access

Creating an interactive and collapsible toolbar on Android

Flutter 1.22 — How to hide BottomNavigationBarItem label text

Bridging Android with ReactNative

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Debanshu Datta

Debanshu Datta

Android @Gojek | Mobile Developer | Backend Developer (Java/Kotlin)

More from Medium

Do you know what is reduce and fold method is in Kotlin?

Extension Functions in Kotlin

A deep dive into Kotlin Coroutines

Delegate your Kotlin Code and Delegating Properties