How do I do a deep copy of a 2D array in Scala?
For example
val a = Array[Array[Int]](2,3)
a(1,0) = 12
I want val b to copy values of a but without pointing to the same array.
How do I do a deep copy of a 2D array in Scala?
For example
val a = Array[Array[Int]](2,3)
a(1,0) = 12
I want val b to copy values of a but without pointing to the same array.
Given:
val a = Array[Array[Int]]
you could try:
for(inner <- a) yield {
for (elem <- inner) yield {
elem
}
}
A deeper question is WHY you would want do do so with ints? The whole point of using immutable types is to avoid exactly this kind of construct.
If you have a more generic Array[Array[T]]
, then your main concern is how to clone the instance of T
, not how to deep-clone the array.