This really depends on whether you need to share that collection widely. The advantage of a mutable collection is that it is usually faster than the immutable collection, and it's easier to have a single object to pass around rather than having to make sure you can set a var from different contexts. But since they can change out from under you, you have to be careful even in a single-threaded context:
import collection.mutable.ArrayBuffer
val a = ArrayBuffer(1,2,3,4)
val i = a.iterator
i.hasNext // True
a.reduceToSize(0)
i.next // Boom!
java.lang.IndexOutOfBoundsException: 0
at scala.collection.mutable.ResizableArray$class.apply(ResizableArray.scala:43)
...
So if it's going to be widely used, you should consider whether you can be appropriately careful to avoid problems like this. It's generally safer to use a var
to an immutable collection; then you might get out of date, but at least you won't fall on your face with a segfault.
var v = Vector(1,2,3,4)
val i = v.iterator
i.hasNext // True
v = Vector[Int]()
i.next // 1
Now, however, you have to pass v
as a return value from any method that might modify it (outside of the class that contains it, at least). This also can cause problems if you forget to update the original value:
var v = Vector(1,2,3,4)
def timesTwo = v.map(_ * 2)
timesTwo
v // Wait, it's still 1,2,3,4?!
But then this doesn't update either, does it?:
a.map(_ * 2) // Map doesn't update, it produces a new copy!
So, as a general rule,
- Performance requires you to use one -- use it
- Local scope within a method -- use mutable collection
- Shared with other threads/classes -- use immutable collection
- Implementation within a class, simple code -- use mutable collection
- Implementation within a class, complex code -- use immutable
but you should probably violate this as often as you stick to it.