9

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
  • Discussion of a similar topic can be found at: <stackoverflow.com/questions/1267436/…> Commented Dec 9, 2009 at 0:00
  • This is not valid code in your example. Can you reformat? Commented Dec 9, 2009 at 1:20

3 Answers 3

12

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)
Sign up to request clarification or add additional context in comments.

1 Comment

This no longer works in Scala 3...
2

Just transpose it twice

a.transpose.transpose

Comments

0

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.

1 Comment

Arrays in Scala are Java arrays and hence mutable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.