August 2017
Intermediate to advanced
440 pages
10h
English
Since Kotlin 1.1, there is an operator, provideDelegate, that is used to provide a delegate during class initialization. The main motivation behind provideDelegate was that it allows us to provide a customized delegate depending on traits of property (name, type, annotations, and so on).
The provideDelegate operator returns a delegate, and types that have this operator do not need to be delegates themselves in order to be used as a delegate. Here is an example:
class A(val i: Int) {
operator fun provideDelegate(
thisRef: Any?,
prop: KProperty<*>
) = object: ReadOnlyProperty<Any?, Int> {
override fun getValue(
thisRef: Any?,
property: KProperty<*>
) = i
}
}
val a by A(1)
In this example, A is used as a delegate, while ...
Read now
Unlock full access