Weird behavior of getting property by reflection

#1

for the following code ,the get() method show an error

Out-projected type ‘KProperty1<out Foo, Any?>’ prohibits the use of ‘public abstract fun get(receiver: T): R defined in kotlin.reflect.KProperty1’



class Foo(){
    val a = 1
}

fun test(){
    val foo = Foo()
    foo::class.memberProperties.find { it.name == "a" }.let{
        it.get(foo)
    }
}

and the IDE show that get() expect a Nothing

how can I get or set the property

my environment

// kotlin
    implementation 'androidx.core:core-ktx:1.1.0-alpha05'
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.3.30"
    implementation 'org.jetbrains.kotlin:kotlin-reflect:1.3.30'
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.1.1"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.1.1"
#2

See explanation here.

Possible workarounds:

Foo::class.memberProperties.find { it.name == "a" }?.get(foo)
(foo::class as KClass<Foo>).memberProperties.find { it.name == "a" }?.get(foo)
1 Like