14

I'm pretty new to Scala and try to understand mutable Seq. Since it's in package mutable I expected there is a method that allows us to append element without copying the whole collection.

But there is no += method in the mutable.Seq, but in Buffer is. :+ and +: both copy the collection.

So why is it mutable?

ZhekaKozlov
  • 32,979
  • 19
  • 111
  • 146
St.Antario
  • 24,791
  • 31
  • 112
  • 278

2 Answers2

27

Because mutable and growable isn't the same thing. (the latter is one specific type of the former: everything, that's growable is mutable, but not everything that's mutable is growable).

mutable.Seq has update, that allows you to change the element at a given index, but it does not grow or shrink. Buffer is s specialization of Seq, that is both mutable and growable.

Dima
  • 36,228
  • 6
  • 41
  • 57
4

As explained in the documentation, mutable.Seq adds an update method to collection.Seq. += on the other hand is defined in Growable.

In Scala standard library, most mutable collections extend the immutable version, which is why they inherit copying :+, +:.

OlivierBlanvillain
  • 7,631
  • 4
  • 31
  • 50
  • 1
    "In Scala standard library, most mutable collections extend the immutable version, which is why they inherit copying `:+`, `+:`." No, they don't. Both mutable and immutable versions (e.g. `collection.mutable.Seq` and `collection.immutable.Seq`) extend a common version (in this case, `collection.Seq`) instead, and that contains `:+` and `+:`. But `collection.mutable.Seq` doesn't extend `collection.immutable.Seq`. – Alexey Romanov Jun 08 '17 at 06:41
  • Indeed, but that that's playing with words. All the methods from `collection.Seq` have "immutable collection" signature, see http://www.scala-lang.org/api/2.12.0/scala/collection/Seq.html#filter(p:A=>Boolean):Repr & co. – OlivierBlanvillain Jun 08 '17 at 08:30