this is my code:
var header1: Record? = null var header2: Record? = null header2 = header1 header2.name = "new_name"
but header1.name
changes too!
For a data class , you can use the compiler-generated copy() method. Note that it will perform a shallow copy. To create a copy of a collection, use the toList() or toSet() methods, depending on the collection type you need. These methods always create a new copy of a collection; they also perform a shallow copy.
You are just assigning the same object (same chunk of memory) to another variable. You need to somehow create a new instance and set all fields. However in Kotlin, if the Record class was Data class, Kotlin would create a copy method for you. And copy method allows you to override the fields you need to override.
You are just assigning the same object (same chunk of memory) to another variable. You need to somehow create a new instance and set all fields.
header2 = Record() header2.name = header1.name
However in Kotlin, if the Record class was Data class, Kotlin would create a copy method for you.
data class Record(val name: String, ...) ... header2 = header1.copy()
And copy method allows you to override the fields you need to override.
header2 = header1.copy(name = "new_name")
If your Class is not a Data Class
and your project has Gson
and you want to copy the whole object ( probably edit after getting it ), Then if all those conditions are true then this is a solution. This is also a DeepCopy. ( For a data Class you can use the function copy()
).
Then if you are using Gson
in your project. Add the function copy()
:
class YourClass () { // Your class other stuffs here fun copy(): YourClass { //Get another instance of YourClass with the values like this! val json = Gson().toJson(this) return Gson().fromJson(json, YourClass::class.java) } }
If you want to install Gson then get the latest version here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With