views:

255

answers:

2

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.

+2  A: 

Discussion of a similar topic can be found at:

http://stackoverflow.com/questions/1267436/what-is-the-easiest-way-to-deeply-clone-copy-a-mutable-scala-object

pyo
A: 

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.

Kevin Wright
Arrays in Scala are Java arrays and hence mutable.
Randall Schulz