Kotlin: Different property delegates for same property

Vairavan Srinivasan
1 min readNov 18, 2023

--

Kotlin’s property delegation is straight forward for most cases. However, there are scenarios where one would like to change the actual delegate based on other runtime conditions.

In the following case, a PropertyDelegateProvider is used to provide different delegates for debug and release versions by overriding operator function provideDelegate.

open class PropertyDelegate<out T>(private val value: T): ReadOnlyProperty<Any?, T> {
override operator fun getValue(thisRef: Any?, property: KProperty<*>): T {
return value
}
}

class DebugPropertyDelegate<out T>(private val value: T): PropertyDelegate<T>(value) {
override operator fun getValue(thisRef: Any?, property: KProperty<*>): T {
// Log in debug version
return value
}
}

class PropertyDelegateProvider<out T>(private val value: T) {
operator fun provideDelegate(
thisRef: Any?,
property: KProperty<*>
): PropertyDelegate<T> {
return when {
isDebug -> DebugPropertyDelegate(value)
else -> PropertyDelegate(value)
}
}
}

The delegate provider can then be used at call site without any runtime checks.

val value by PropertyDelegateProvider(10)

--

--