11.2. Creating a Mutable List
Problem
You want to use a mutable list (a LinearSeq, as opposed to an IndexedSeq), but a List isn’t mutable.
Solution
Use a ListBuffer, and convert
the ListBuffer to a List when needed.
The following examples demonstrate how to create a ListBuffer, and then add and remove elements,
and then convert it to a List when
finished:
importscala.collection.mutable.ListBuffervarfruits=newListBuffer[String]()// add one element at a time to the ListBufferfruits+="Apple"fruits+="Banana"fruits+="Orange"// add multiple elementsfruits+=("Strawberry","Kiwi","Pineapple")// remove one elementfruits-="Apple"// remove multiple elementsfruits-=("Banana","Orange")// remove multiple elements specified by another sequencefruits--=Seq("Kiwi","Pineapple")// convert the ListBuffer to a List when you need tovalfruitsList=fruits.toList
Discussion
Because a List is immutable, if
you need to create a list that is constantly changing, the preferred
approach is to use a ListBuffer while
the list is being modified, then convert it to a List when a List is needed.
The ListBuffer Scaladoc states
that a ListBuffer is “a Buffer implementation backed by a list. It
provides constant time prepend and append. Most other operations are
linear.” So, don’t use ListBuffer if
you want to access elements arbitrarily, such as accessing items by
index (like list(10000)); use
ArrayBuffer instead. See Recipe 10.4 for more information.
Although you can’t modify the elements ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access