Kotlin-jvm和Kotlin-js之间KClass的不同行为



我写了一些kotlin代码来显示jvm和js中执行之间的行为差异。我该怎么解决这个问题?

此等式:booleanKClass==genericKclass对于JVM为true,但对于JS 为false

我将粘贴代码,然后是控制台生成的输出(一个用于jvm,一个用于js(如果你从一个多平台项目调用test1((,你会像我一样看到它。我使用的是kotlin_version='1.2.51'

fun test1() {
val values = PropertyDelegate()
val result = Result(values)
println("This will call the delegate getter.")
println("result.success is not really important but: ${result.success}")
println("This will call the delegate setter...")
result.success = true
println("end")
}
class Result(del: PropertyDelegate) {
var success: Boolean by del
}
class PropertyDelegate() {
inline operator fun <reified T> getValue(thisRef: Any?, property: KProperty<*>): T {
val booleanKClass = Boolean::class
val genericKclass = T::class
println("getValue (booleanKClass == genericKclass) is ${booleanKClass == genericKclass}")
return true as T
}
inline operator fun <reified T> setValue(thisRef: Any?, property: KProperty<*>, value: T) {
val booleanKClass = Boolean::class
val genericKclass = T::class
println("setValue (booleanKClass == genericKclass) is ${booleanKClass == genericKclass}")
}
}

JVM输出:

This will call the delegate getter.
getValue (booleanKClass == genericKclass) is true
result.success is true
This will call the delegate setter...
setValue (booleanKClass == genericKclass) is true
end

JS输出:

This will call the delegate getter.
getValue (booleanKClass == genericKclass) is false
result.success is not really important but: true
This will call the delegate setter...
setValue (booleanKClass == genericKclass) is false
end

从Kotlin 1.3.41开始,它就可以正常工作。

打印:

This will call the delegate getter.
getValue (booleanKClass == genericKclass) is true
result.success is not really important but: true
This will call the delegate setter...
setValue (booleanKClass == genericKclass) is true
end

最新更新