Matthieu Stombellini
07/14/2022, 8:37 PMprovideDelegate
to work with generic output types. Basically, what I'm trying to do is the following setup:
class Producer {
inline fun <reified T> create(): ReadOnlyProperty<Any, T> {
println("Creating a property with create(), return type is ${T::class}")
TODO()
}
inline operator fun <reified T> provideDelegate(thisRef: Any, prop: KProperty<*>): ReadOnlyProperty<Any, T> {
println("Creating a property with provideDelegate, return type is ${T::class}")
TODO()
}
}
class MyClass(producer: Producer) {
val one: String by producer.create()
//val two: String by producer
}
While the val one
works perfectly fine, if I uncomment val two
, it no longer compiles. Is there any way to do this? Kotlin Playground link: https://pl.kotl.in/vXOAoeauS
Compilation fails with:
Property delegate must have a 'provideDelegate(MyClass, KProperty<*>)' method. None of the following functions is suitable: public final inline operator fun <reified T> provideDelegate(thisRef: Any, prop: KProperty<*>): ReadOnlyProperty<Any, ???> defined in Producer
Youssef Shoaib [MOD]
07/15/2022, 7:46 AMKProperty
inside create, then make create return a PropertyDelegateProvider
instead like so:
import kotlin.reflect.*
import kotlin.properties.*
class Producer {
inline fun <reified T> create(): PropertyDelegateProvider<Any?, ReadOnlyProperty<Any?, T>> = PropertyDelegateProvider { _, prop ->
println("Creating a property with provideDelegate, return type is ${T::class}")
TODO()
}
}
class MyClass(producer: Producer) {
val one: String by producer.create()
val two: String by producer.create()
}
fun main() {
val obj = MyClass(Producer()) // will fail immediately because of the TODO()s, that's normal
}