Skip to content

Instantly share code, notes, and snippets.

@ryanlecompte
Created July 9, 2013 23:21
Show Gist options
  • Save ryanlecompte/5962188 to your computer and use it in GitHub Desktop.
Save ryanlecompte/5962188 to your computer and use it in GitHub Desktop.
// cheap way to deep clone an arbitrarily-deep nested array
def deepCopy[T](array: Array[T]): Array[T] = {
import java.io._
val bos = new ByteArrayOutputStream()
val oos = new ObjectOutputStream(bos)
oos.writeObject(array)
val bis = new ByteArrayInputStream(bos.toByteArray)
val ois = new ObjectInputStream(bis)
ois.readObject().asInstanceOf[Array[T]]
}
scala> val a = Array(Array(1,2,3), Array(4,5,6), Array(7,8,9))
a: Array[Array[Int]] = Array(Array(1, 2, 3), Array(4, 5, 6), Array(7, 8, 9))
scala> val c = deepCopy(a)
c: Array[Array[Int]] = Array(Array(1, 2, 3), Array(4, 5, 6), Array(7, 8, 9))
scala> a(0)(0) = 9999
scala> a
res3: Array[Array[Int]] = Array(Array(9999, 2, 3), Array(4, 5, 6), Array(7, 8, 9))
scala> c
res4: Array[Array[Int]] = Array(Array(1, 2, 3), Array(4, 5, 6), Array(7, 8, 9))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment