This is more a question of style and preference but here goes: when should I use scala.Array? I use List all the time and occasionally run into Seq, Map and the like, but I’ve never used nor seen Array in the wild. Is it just there for Java compatibility? Am I missing a common use-case?
Share
First of all, let’s make a disclaimer here. Scala 2.7’s
Arraytries to be a JavaArrayand a Scala Collection at the same time. It mostly succeeds, but fail at both for some corner cases. Unfortunately, these corner cases can happen to good people with normal code, so Scala 2.8 is departing from that.On Scala 2.8, there’s
Array, which is JavaArray. That means it is a contiguous memory space, which stores either references or primitives (and, therefore, may have different element sizes), and can be randomly accessed pretty fast. It also has lousy methods, an horribletoStringimplementation, and performs badly when using generics and primitives at the same time (eg:def f[T](a: Array[T]) = ...; f(Array(1,2,3))).And, then, there is
GenericArray, which is a Scala Collection backed by anArray. It always stores boxed primitives, so it doesn’t have the performance problems when mixing primitives and generics but, on the other hand, it doesn’t have the performance gains of a purely primitive (non-generic) primitive array.So, when to use what? An
Arrayhas the following characteristics:If you don’t need generics, or your generics can be stated as
[T <: AnyRef], thus excluding primitives, which areAnyVal, and those characteristics are optimal for your code, then go for it.If you do need generics, including primitives, and those characteristics are optimal for your code, use
GenericArrayon Scala 2.8. Also, if you want a true Collection, with all of its methods, you may want to use it as well, instead of depending on implicit conversions.If you want immutability or if you need good performance for append, prepend, insert or delete, look for some other collection.