Delegated properties are one of the best features of Kotlin language. We have already seen observable and vetoable delegates. In this recipe, we will learn how to create our own custom delegate. As a demo example, we will create a delegate property that can only be initialized once; if done again, it should throw an exception. So let's dive into it and see how we can achieve it.
We will be using IntelliJ IDEA for coding purposes. You can use any IDE capable of executing Kotlin code.
Now, let's dive in and learn how to create our own delegates:
- Let's create a custom delegate named as
SingleInitializationProperty
. This custom delegate property will throw an exception if the variable isn't initialized, and it can only be initialized once. Doing it a second time will throw an exception. Let's take a look at our custom delegate class:
class SingleInitializableProperty<T>() : ReadWriteProperty<Any?, T>{ private var value: T? = null...