15

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
  • 36,558
  • 20
  • 126
  • 155
St.Antario
  • 26,175
  • 41
  • 130
  • 318

2 Answers2

28

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
  • 39,570
  • 6
  • 44
  • 70
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,701
  • 4
  • 32
  • 51
  • 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