2

I wrote some kotlin code to show a difference of behavior between the execution on jvm and in js. How could I fix this?

This equality: booleanKClass == genericKclass is true for JVM but false for JS

I’m going to paste the code followed by the output generated by the console (one for jvm and one for js) If you call test1() from a multiplatform project you will see this as I did. I’m using 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 output:

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 output:

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
Jako
  • 2,489
  • 3
  • 28
  • 38
  • Fun. I don't see why this shouldn't work, even with limitations in https://kotlinlang.org/docs/reference/js-reflection.html. In JS, `genericKclass` is shown as `class null`. – Alexey Romanov Jul 19 '18 at 10:13
  • Feel free to vote related issues https://youtrack.jetbrains.com/issue/KT-23178 https://youtrack.jetbrains.com/issue/KT-17527 – bashor Dec 11 '18 at 13:04
  • 1
    JFYI: the issues are fixed. – bashor Jul 08 '19 at 17:44

1 Answers1

3

It works as expected since Kotlin 1.3.41.

Prints:

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
bashor
  • 8,073
  • 4
  • 34
  • 33