I'm working with a third-party library that has a function which expects an argument of type KProperty1<T, V>, and casts it to an instance of CallableReference internally. I need to acquire a reference to a class member through reflection that is an instance of both KProperty1 and CallableReference.
The function in the third-party library looks something like this:
fun <T : Any, V> thirdPartyFunction(property: KProperty1<T, V>) {
val callableReference = (property as CallableReference)
}
Everything works when I call the function with a member reference obtained with the :: operator:
class ExampleClass(
var exampleProperty: String,
)
// this works
thirdPartyFunction(ExampleClass::exampleProperty)
When I call the function with a value obtained through reflection, I get a ClassCastException:
val reflectedProperty = ExampleClass::class.memberProperties
.find { it.name == "exampleProperty" } as KProperty1<ExampleClass, String>
// class kotlin.reflect.jvm.internal.KMutableProperty1Impl cannot be cast to class kotlin.jvm.internal.CallableReference
thirdPartyFunction(reflectedProperty)
I'm using Kotlin 1.9.21 on the JVM.
KClass". It may be tricky or even impossible to use it as you need.KClass"? That's a weird restriction to impose...KPropertywas provided.