2

I want to get a JavaScript object loaded into a Kotlin class. As a safety check, I need to verify that the Kotlin object is actually the class I’ve created because some JavaScript code parts are not my design. I need the JavaScript to return correctly, but I cannot verify the Kotlin class.

e.g.

JavaScript object

<script id="myJS">
function MyClass(id, name){
    var obj = {};
    obj.id = id;
    obj.name = name;

    return obj;
}
var myClass = MyClass(0, "name_0");
</script>

Kotlin class

class MyClass(
            val id: Int,
            val name: String
)

I use this Kotlin code to get JavaScript object on Kotlin.

val myJS: dynamic = document.getElementById("myJS")
val myClass: MyClass = JSON.parse<MyClass>(JSON.stringify(myJS.myClass))//get JavaScript object
println(myClass.id)//success output "0"
println(myClass.name)//success output "name_0"

println(myClass is MyClass)//but check class this output "false"

How can I verify the JavaScript object is the created Kotlin class?

iHad 169
  • 1,267
  • 1
  • 10
  • 16

3 Answers3

2

Use JSON.parse from kotlinx.serialization library instead of JSON.parse from Kotlin/JS standard library.

JSON from Kotlin standard library is just a view around JavaScript JSON object . So JSON.parse creates regular JS object without any information about Kotlin type.

Its fine to use it with external classes that can't be type-checked. But your MyClass is a regular class.

Objects constructed from regular Kotlin classes have special metadata which is essential for type checks myClass is MyClass and reflection myClass::class == MyClass::class. And kotlinx.serialization library creates these full-featured Kotlin objects.

kzm
  • 373
  • 3
  • 12
0

Try this check :

myClass::class == MyClass::class
0

This might be helpful:

class MyClass(val id: Int, val name: String) {
    constructor(obj: dynamic): this(obj.id, obj.name)

    override fun toString(): String = 
        "${this.id} ${this.name}"
}

fun main() {

    val obj  = js("{}")
    obj.id   = 1
    obj.name = "Mike"

    val myObj = MyClass(obj)
    println(myObj)
    println(myObj is MyClass)
}
tomschrot
  • 219
  • 1
  • 2
  • 4
  • I try if then obj.id="Mike" . It will be println(myObj is MyClass) output "true". But, println(myObj.id) output "Mike" and println(myObj.id is Int) output "false". I try if then or obj.id=null . It will be println(myObj is MyClass) output "true". But, println(myObj.id) output null and println(myObj.id is Int) output "false". – iHad 169 Nov 14 '18 at 08:01
  • Change MyClass primary ctor to null aware fields: class MyClass(val id: Int?, val name: String?) But will have to null check your class members... – tomschrot Nov 14 '18 at 08:25
  • p.s. what compiler version are you using, which options? – tomschrot Nov 14 '18 at 08:29
  • Kotlin Compiler Version 1.3 – iHad 169 Nov 15 '18 at 07:24