https://kotlinlang.org logo
#javascript
Title
# javascript
c

Császár Ákos

10/30/2023, 12:21 PM
Hi! I added an npm package to my KMP project, which contains an extension for the Window.
Copy code
external class Window {
    fun init(url: String): Promise<MyResponse>
}

class MyResponse{
    val message: String? = null
    val status: String? = null
}
In the following code, the function call and even the .await() is working, but I think the conversion from json object to MyResponse is not.
Copy code
val response = window.init("url").await()

console.log("init",response). //logs out as json object instead of MyResponse, and all fields have values.
console.log("message: ", response.message). // will be undefined
Can someone explain me what am I doing wrong?
window.init("url").await().asDynamic().message
works fine, but I want the use the response as a class. Is it possible?
a

Artem Kobzar

10/30/2023, 5:08 PM
Kotlin doesn't convert js objects into class instances automatically. To achieve convertion you should to write the transformation manually. As an example:
Copy code
external interface InitResponse {
  val message: String?
  val status: String?
} 
external class Window {
  fun init(url: String): Promise<InitResponse>
}
class MyResponse(val message: String?, val status: String?)
fun InitResponse.toMyResponse() = MyResponse(message, status)
And you could use it in your code as:
Copy code
window.init("url").await().toMyResponse()
👍 1
e

Edoardo Luppi

11/01/2023, 1:10 PM
@Artem Kobzar can't we just use the
Copy code
external interface InitResponse {
  val message: String?
  val status: String?
}
directly at that point? Without the additional class MyResponse.
a

Artem Kobzar

11/01/2023, 1:18 PM
Sure, I shared the example with the class only because the original question contains such a conversion.
✔️ 1
e

Edoardo Luppi

11/01/2023, 1:44 PM
@Artem Kobzar asked because I was doubting the understanding I had built up in the past months 😂 didn't want to go back and rewrite lol
K 1
c

Császár Ákos

11/03/2023, 10:50 AM
Yes, thats what I was looking for. Thanks!
2 Views