Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
比较kotlin中对象的常用属性值_Kotlin_Kotlin Reflect - Fatal编程技术网

比较kotlin中对象的常用属性值

比较kotlin中对象的常用属性值,kotlin,kotlin-reflect,Kotlin,Kotlin Reflect,我正在尝试编写一个方法来比较Kotlin中两个对象的“公共属性”(共享相同的名称/类型)。它用于测试中,用于比较“预期”对象和不属于同一类型的“实际”对象 这是迄今为止代码的简化版本: val obj1Props = obj1::class.memberProperties val obj2Props = obj2::class.memberProperties val commonPropertyPairs = obj1Props.map { obj1Prop ->

我正在尝试编写一个方法来比较Kotlin中两个对象的“公共属性”(共享相同的名称/类型)。它用于测试中,用于比较“预期”对象和不属于同一类型的“实际”对象

这是迄今为止代码的简化版本:

val obj1Props = obj1::class.memberProperties
val obj2Props = obj2::class.memberProperties

val commonPropertyPairs  = obj1Props.map { obj1Prop ->
        obj1Prop to obj2Props.find { obj2Prop -> obj1Prop.name == obj2Prop.name } }
    .filter { pair -> pair.second != null }

commonPropertyPairs.forEach { pair ->
  pair.first.get(obj1)
}
我当前在底部附近的“pair.first.get”下收到此错误消息:

out projected type
KProperty1
禁止使用kotlin.reflect.KProperty1


我明白我显然不能使用抽象方法,我应该怎么做呢?

而不是
obj1::class.memberProperties
你需要使用
SomeClass::class.memberProperties
,例如:

override fun buildNavItem() {
    val obj1 = "Hello"
    val obj2 = 10
    val obj1Props = String::class.memberProperties
    val obj2Props = Int::class.memberProperties

    val commonPropertyPairs  = obj1Props.map { obj1Prop ->
        obj1Prop to obj2Props.find { obj2Prop -> obj1Prop.name == obj2Prop.name } }
            .filter { pair -> pair.second == null }

    commonPropertyPairs.forEach { pair ->
        pair.first.get(obj1)
    }
}
产生这种差异的原因是,当使用
SomeClass::class
引用时,它必然是表示
SomeClass
的类标记,而不是其可能的派生类之一,因此它是没有预测类型的
KClass