Tom Jinaad
Tom Jinaad

Reputation: 109

Deep copy of 2D array in Scala?

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.

Upvotes: 9

Views: 5363

Answers (3)

ayvango
ayvango

Reputation: 5977

Just transpose it twice

a.transpose.transpose

Upvotes: 2

Leo
Leo

Reputation: 777

You can use the clone method of the Array class. For a multi-dimensional Array, use map on the extra dimensions. For your example, you get

val b = a.map(_.clone)

Upvotes: 12

Kevin Wright
Kevin Wright

Reputation: 49705

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.

Upvotes: 0

Related Questions