Can the copy function of data classes be used in K...
# javascript
a
Can the copy function of data classes be used in KotlinJS? I get "Uncaught TypeError: copy is not a function"
t
You need custom named wrapper for generic case
a
How would this need to look like?
Can you give an example?
t
Copy code
data class D(val a: Int) {
    @JsName("copy")
    fun jsCopy(val a: Int?): D = copy(a = a)
}
I think you want copy with single options parameter. Right?
Options will be more flexible in this case
@Alexander Weickmann Options example - https://pl.kotl.in/3fHjFCNQ6
But I think in JS world must be used spread operator on plain data object instead for clear solution and #serialization on Kotlin side
a
@turansky it works, but we cannot add this code to the multiplatform common module data class 😞
t
Do you use IR?
a
we found a solution:
Copy code
@Suppress("UnsafeCastFromDynamic")
fun <T> T.jsCopy(options: dynamic.() -> Unit): T {
    val o = this
    val copyObj = js("Object.assign({}, o)")

    val optionsObj = jsObject(options)
    Object.keys(optionsObj).forEach { key ->
        val descriptor = Object.getOwnPropertyDescriptor<RProps>(optionsObj, key)
        Object.defineProperty(copyObj, key, descriptor)
        undefined
    }

    return copyObj as T
}

inline fun jsObject(init: dynamic.() -> Unit): dynamic {
    val o = js("{}")
    init(o)
    return o
}
what is IR?
t
Looks like you create unsafe #serialization
IR - new compiler (in alpha now)
a
no, we are not using the alpha compiler. what do you mean by unsafe serialization? is there another approach available how we could do this? we are using react / redux and it is very important to have the ability to copy objects with a certain value being changed.
t
I use legacy compiler too. I use
DynamicObjectParser
for converting Data classes to JSO, on JS side I use spread operator - standard JS functionality.
@Alexander Weickmann Do you need example of such solution? I have one