How can I duplicate an object to another object, w

2019-06-22 16:52发布

问题:

this is my code:

var header1: Record? = null
var header2: Record? = null

header2 = header1
header2.name = "new_name"

but header1.name changes too!

回答1:

You are just assigning the same object (same chunk of memory) to another variable. You need to somehow crate 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 fields you need to override.

header2 = header1.copy(name = "new_name")


回答2:

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);

See: Is Java "pass-by-reference" or "pass-by-value"?



回答3:

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 = jack.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.