Deep copy object in Javascript?


#1

With plain JS objects, you can create a simple deep copy like this:

var copy = JSON.parse(JSON.stringify(obj));

If I do this with an instance of a class that’s written in Kotlin, is it going to cause problems? Maybe I need to write custom copy methods for my classes.

thanks,
Rob


#2

Serialization and deserialization of object only in order to copy new instance is a very ugly hack. Never use it even in js. If you want to deep copy your objects you need to implement Cloneable interface


#3

Cloneable is not available in the JS backend (see KT-6639). I’ll probably just implement a custom copy method.


#4

It would be really nice if the data class generated copy() method was deep. I understand that Any doesn’t have ‘copy’, but the compiler could check for a copy() method on the data class’s members when auto-generating the copy() method.

(And yes, I know that you can always write your own copy() method, but that’s tedious and why we’re lazy and use serialization to clone!)

data class Foo(val a: Int, val b: Bar) {

// It’d be awesome if the compiler could generate the copy method like this:
fun copy(): Foo {
return Foo(a, b.copy())
}

// Instead of how it is now:
fun copy(): Foo {
return Foo(a, b)
}
}

data class Bar(val c: Int)