0

I have an ArrayList which is assigned to two ArrayList variables. So it assigned the memory location of the primary to the other two. But I need a variable that should not change the parent and another one.

data class Item(
    var id: Int,
    var name: String
)


val master: Arraylist<Item> = items // from network
val copy1 = master
val copy2 = master

copy2[0].name = "new name here"

From the above code, we are changing the name of all. But my requirement is to make a copy of the master and change it only in copy2

KIRAN K J
  • 632
  • 5
  • 28
  • 57
  • Are you sure your example code is correct? The variable `copy2` has the same type as `master` which is an `ArrayList`, not an `Item`. So I do not think that it is possible to call `copy2.name`. – Karsten Gabriel Mar 04 '22 at 12:01
  • 1
    @vincrichaud I already went through these answers. I will agin check and update. Also, if I assign an item from the list to a variable `val item = master.get(0)`. If i changes the item property, it will also affect all three. I need this scenario (single item assignment) too. – KIRAN K J Mar 04 '22 at 13:03
  • @KarstenGabriel Extremely sorry. Updated the question – KIRAN K J Mar 04 '22 at 13:06

1 Answers1

1

You can create a copy of your master list by copying all contained items:

fun List<Item>.copy() = map{ it.copy() }

Then, when you write

val copy2 = master.copy()

You have a copy of master consisting of (shallow) copies of the contained elements in master.

(see Kotlin documentation on copying data classes)

Now changing elements in copy2 does not change the corresponding elements in master or copy1.

Karsten Gabriel
  • 3,115
  • 6
  • 19