Deep copy of a 2D array in Scala?

How to make 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 the values โ€‹โ€‹of a, but not pointing to the same array.

+6
arrays scala deep-copy
source share
3 answers

You can use the clone method of the Array class. For multidimensional Array use map extra dimensions. For your example, you get

 val b = a.map(_.clone) 
+5
source share

Just carry it over twice

 a.transpose.transpose 
+1
source share

Given:

 val a = Array[Array[Int]] 

you can try:

 for(inner <- a) yield { for (elem <- inner) yield { elem } } 

The deeper question: WHY do you want to do this with ints? The whole point of using immutable types is to avoid such a construction.

If you have a more general Array[Array[T]] , then your main problem is how to clone an instance of T , and not how to deeply clone an array.

0
source share

All Articles