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?

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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 :+, +:.

2 Comments

"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.
Indeed, but that that's playing with words. All the methods from collection.Seq have "immutable collection" signature, see scala-lang.org/api/2.12.0/scala/collection/… & co.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.