this is my code:
var header1: Record? = null
var header2: Record? = null
header2 = header1
header2.name = "new_name"
but header1.name
changes too!
this is my code:
var header1: Record? = null
var header2: Record? = null
header2 = header1
header2.name = "new_name"
but header1.name
changes too!
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.
You got 2 options use the copy method if the second object needs to be exactly the same or some of a fields needs to be changed.
val alex = User(name = "Alex", age = 1)
val olderAlex = alex.copy(age = 2)
or Kotlin got the great syntax of constructing object I mean, e.g.
createSomeObject(obj = ObjInput(name = objName,
password = UUID.randomUUID().toString()
type = listOf(TYPE)))
In fact, It seems to be easier in your case use first one but good to know about the second way to resolve this task.
You have to create a new instance of the variable and initialize every field. If you just do header2 = header1
you are also passing the reference of header1
to header2
.
Example (Java):
public Record(Record record) {
this.name = record.name;
}
Then call it as: header2 = new Record(header1);