我写了一些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
答案 0 :(得分:2)
自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