The elements of the original table are still modified after cloning


I have the following code:

val copyA = a.clone
copyA(0)(0) = 1
println("a(0)(0): " + a(0)(0))

This prints:

a(0)(0): 1

If I change it to this:

val copyA = a.clone
println("a(0)(0): " + a(0)(0))

It prints:

a(0)(0): 0

So why is a affected by a change in copyA?

How can I make it such that changes in copyA don't affect a?

Mutating the cloned 1D array instance won't change the original instance and vice-versa,


scala> val original = Array(100, 200)
original: Array[Int] = Array(100, 200)

scala> val cloned = original.clone
cloned: Array[Int] = Array(100, 200)

mutating cloned array does not affect original array,

scala> cloned(0) = 5000

scala> original(0) //still the same value
res36: Int = 100

mutating original array does not affect cloned array,

scala> original(0) = 8888

scala> cloned(0) // still the same
res38: Int = 5000

But its different regarding 2D array, because each array inside is a ref and has to be deep cloned

scala> val original = Array.ofDim[Int](2,2)
original: Array[Array[Int]] = Array(Array(0, 0), Array(0, 0))

scala> original.foreach {col => println(col)}
[[email protected]
[[email protected]

deep cloning 2D array

scala> val cloned =
cloned: Array[Array[Int]] = Array(Array(0, 0), Array(0, 0))

scala> original(0)(0) = 5000

scala> cloned(0)(0)
res43: Int = 0

//changing cloned does not change original array
scala> cloned(0)(0) = 8888

scala> original(0)(0)
res48: Int = 5000