2

我写了一些 kotlin 代码来展示在 jvm 和 js 中执行之间的行为差​​异。我该如何解决这个问题?

这个等式: booleanKClass == genericKclass对于 JVM 是 true, 但对于 JS是false

我将粘贴代码,然后是控制台生成的输出(一个用于 jvm,一个用于 js) 如果您从多平台项目调用 test1(),您将看到这一点。我正在使用 kotlin_version = '1.2.51'</p>

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
4

1 回答 1

3

它从 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
于 2019-07-08T18:28:17.547 回答