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

SadeQ digitALLife

this is my code:

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

header2 = header1
header2.name = "new_name"

but header1.name changes too!

Josef Adamcik

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Java - How can I add an object to a list of another object

How can I access an object within another object's method?

How to duplicate object properties in another object?

How can I add an object inside another object in Javascript?

How can I copy an object of another class?

How can I make an object using another object in Java?

How can I get address of an object in Kotlin?

How can I Map Object Array To Array With Identifier For Duplicate Values?

How can I extend my graphql object into my Kotlin object?

How can I map an Object into another one?

How can I move slowly smooth object to be child of another object?

DJANGO - how can I filter an object filtering by another object filtered

If I have an object that is a property of another object, how can I reference the main object from the property object?

How can I create object of repository without having constructor values in Android-Kotlin?

How can I duplicate a domain object in Grails?

How do I rotate a graphics object, without changing it's location?

How can I flatten this object stream without creating duplicate objects?

How can I pass the same object to another method of another object?

How to extend A object to AB object, without affecting A object when I insert another value to AB object?

How can I delete duplicate items in ArrayList <Object> with LinkedHashSet?

How can I move some object in circle around another object?

How can I move a object to another object center?

How can i match an value of the arrays object with another object?

Changing the property of base object

How do I remove 1 property without changing object, so I can add content to tablecells?

How can I access an object in another method?

Angular: How can I 'nest' an object in another object?

How can I map over an object and set it to another object without overwriting the previous values?

Can I modify an object stored in a react state hook without having to duplicate that object?