Why no immutable arrays in scala standard library?

前端 未结 7 1535
死守一世寂寞
死守一世寂寞 2020-12-23 21:27

Scala has all sorts sorts of immutable sequences like List, Vector,etc. I have been surprised to find no implementation of immutable indexed sequence backed by a simple arra

相关标签:
7条回答
  • 2020-12-23 22:17

    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.

    0 讨论(0)
提交回复
热议问题