Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I duplicate an object to another object, without changing the base object in Kotlin?

Tags:

this is my code:

var header1: Record? = null var header2: Record? = null  header2 = header1 header2.name = "new_name" 

but header1.name changes too!

like image 693
SadeQ digitALLife Avatar asked May 08 '18 15:05

SadeQ digitALLife


People also ask

How do you duplicate an object in Kotlin?

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.

How do you assign one object to another in Kotlin?

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.


2 Answers

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") 
like image 199
Josef Adamcik Avatar answered Oct 04 '22 16:10

Josef Adamcik


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.

like image 21
Xenolion Avatar answered Oct 04 '22 16:10

Xenolion