Teodorico Levoff Teodorico Levoff - 24 days ago 8
Scala Question

Cloning ListBuffer immutable issue Scala

I have a

var x
of type
ListBuffer[ListBuffer[Int]]
in which I am cloning using the function
clone
and setting to another
var y
, I then use the function
update
on this new
vary
to update the contents, but when I check the original contents of
var x
it is the same as
var y
? Why is this? What am I doing wrong? Is their a workaround? I am trying to achieve a copy of ListBuffer that I can modify without changing the original contents of the initial ListBuffer.

Answer

clone only makes a shallow copy, you need a deep copy:

scala> import collection.mutable.ListBuffer
import collection.mutable.ListBuffer

scala> var a = ListBuffer(ListBuffer(1, 2), ListBuffer(3,4))
a: scala.collection.mutable.ListBuffer[scala.collection.mutable.ListBuffer[Int]] = ListBuffer(ListBuffer(1, 2), ListBuffer(3, 4))


scala> var b = a.clone
b: scala.collection.mutable.ListBuffer[scala.collection.mutable.ListBuffer[Int]] = ListBuffer(ListBuffer(1, 2), ListBuffer(3, 4))

scala> b(0)(0) = 100

scala> a
res1: scala.collection.mutable.ListBuffer[scala.collection.mutable.ListBuffer[Int]] = ListBuffer(ListBuffer(100, 2), ListBuffer(3, 4))

scala> b
res2: scala.collection.mutable.ListBuffer[scala.collection.mutable.ListBuffer[Int]] = ListBuffer(ListBuffer(100, 2), ListBuffer(3, 4))

scala> var c = a.clone.map(_.clone)
c: scala.collection.mutable.ListBuffer[scala.collection.mutable.ListBuffer[Int]] = ListBuffer(ListBuffer(100, 2), ListBuffer(3, 4))

scala> c(0)(0) = 1000

scala> c
res3: scala.collection.mutable.ListBuffer[scala.collection.mutable.ListBuffer[Int]] = ListBuffer(ListBuffer(1000, 2), ListBuffer(3, 4))

scala> a
res4: scala.collection.mutable.ListBuffer[scala.collection.mutable.ListBuffer[Int]] = ListBuffer(ListBuffer(100, 2), ListBuffer(3, 4))