Why no immutable arrays in scala standard library?
So, let's first make a distinction between interface and class. The interface is an API design, while the class is the implementation of such API.
The interfaces in Scala have the same name and different package to distinguish with regards to immutability: Seq
, immutable.Seq
, mutable.Seq
.
The classes, on the other hand, usually don't share a name. A List
is an immutable sequence, while a ListBuffer
is a mutable sequence. There are exceptions, like HashSet
, but that's just a coincidence with regards to implementation.
Now, and Array
is not part of Scala's collection, being a Java class, but its wrapper WrappedArray
shows clearly where it would show up: as a mutable class.
The interface implemented by WrappedArray
is IndexedSeq
, which exists are both mutable and immutable traits.
The immutable.IndexedSeq
has a few implementing classes, including the WrappedString
. The general use class implementing it, however, is the Vector
. That class occupies the same position an Array
class would occupy in the mutable side.
Now, there's no more complexity in using a Vector
than using an Array
, so I don't know why you call it complicated.
Perhaps you think it does too much internally, in which case you'd be wrong. All well designed immutable classes are persistent, because using an immutable collection means creating new copies of it, so they have to be optimized for that, which is exactly what Vector
does.
Mostly because there are no arrays whatsoever in Scala. What you're seeing is java's arrays pimped with a few methods that help them fit into the collection API.
Anything else wouldn't be an array, with it's unique property of not suffering type erasure, or the broken variance. It would just be another type with indexes and values. Scala does have that, it's called IndexedSeq
, and if you need to pass it as an array to some 3rd party API then you can just use .toArray