Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append or prepend on a Scala mutable.Seq

There's something I don't understand about Scala's collection.mutable.Seq. It describes the interface for all mutable sequences, yet I don't see methods to append or prepend elements without creating a new sequence. Am I missing something obvious here?

There are :+ and +: for append and prepend, respectively, but they create new collections — in order to be consistent with the behavior of immutable sequences, I assume. This is fine, but why is there no method like += and +=:, like ArrayBuffer and ListBuffer define, for in-place append and prepend? Does it mean that I cannot refer to a mutable seq that's typed as collection.mutable.Seq if I want to do in-place append?

Again, I must have missed something obvious, but cannot find what…

like image 604
Jean-Philippe Pellet Avatar asked Jul 08 '11 14:07

Jean-Philippe Pellet


People also ask

Is seq mutable in Scala?

Scala's default Seq class is mutable. Yes, you read that right.

What is the difference between SEQ and list in Scala?

A Seq is an Iterable that has a defined order of elements. Sequences provide a method apply() for indexing, ranging from 0 up to the length of the sequence. Seq has many subclasses including Queue, Range, List, Stack, and LinkedList. A List is a Seq that is implemented as an immutable linked list.

Is array mutable in Scala?

Array in scala is homogeneous and mutable, i.e it contains elements of the same data type and its elements can change but the size of array size can't change.


1 Answers

Mutability for sequences only guarantees that you'll be able to swap out the items for different ones (via the update method), as you can with e.g. primitive arrays. It does not guarantee that you'll be able to make the sequence larger (that's what the Growable trait is for) or smaller (Shrinkable).

Buffer is the abstract trait that contains Growable and Shrinkable, not Seq.

like image 92
Rex Kerr Avatar answered Sep 22 '22 09:09

Rex Kerr