Kotlin: Scoping property delegates

Vairavan Srinivasan
1 min readSep 23, 2023

Kotlin’s property delegates helps abstract details like how a dependency is provided like how an Android view is resolved from the layout hierarchy.

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

The above property delegate can be used for `vals` and can be used for delegation from any context like the following

fun main() {
val value by PropertyDelegate(10)
}

However, there are cases where restricting the scope for property delegation makes more sense like an Android property delegate to find a view by id makes sense only in the context of Activity or Fragment and not in any other context. This can be achieved via following

class ViewDelegate<out T>(private val resId: Int): ReadOnlyProperty<Activity, T> {
override operator fun getValue(thisRef: Activity, property: KProperty<*>): T {
return thisRef.findViewById(resId)
}
}

class MainActivity : ComponentActivity() {
private val button by ViewDelegate<Button>(R.id.button)
}

Trying to use the above delegate in any other context (other than Activity) will cause a compilation error.

--

--