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

梦想与她 提交于 2019-12-10 12:49:55

问题


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.



来源:https://stackoverflow.com/questions/50237384/how-can-i-duplicate-an-object-to-another-object-without-changing-the-base-objec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!