I have run into this scenario several times recently:
- a class has an immutable (indexed?) sequence member
- a factory member method creates a new instance with the sequence somewhat modified
What's an efficient way to do this?
class A( xs: IndexedSeq[Int] ) {
def another: A = {
val ys = xs.toArray.clone() // !!!
ys(7) = 13
new A(ys)
}
}
I do .toArray so that I can modify this sequence in place and .clone because I'm afraid that if the original xs was an array already, toArray will just return this and I will modify the objects (meant-to-be-immutable) values. However, this obviously makes two copies if xs was not an Array and I would really like to avoid that. Obviously, I could just check its type, but that seems very inelegant and I'm not too sure if I'd have to check against other mutable sequences which can wrap an Array. What do?
scala> val xs: Seq[Int] = Array(1, 2, 3)
ss: Seq[Int] = WrappedArray(1, 2, 3)
scala> val ys = xs.toArray
ys: Array[Int] = Array(1, 2, 3)
scala> ys(1) = 22
scala> ys
res1: Array[Int] = Array(1, 22, 3)
scala> xs
res2: Seq[Int] = WrappedArray(1, 22, 3)