Removing an item from a MutableList in Scala

I have a MutableList and I want to remove an element from it, but I cannot find the appropriate method. There is a way to remove an item from a ListBuffer as follows:

 val x = ListBuffer(1, 2, 3, 4, 5, 6, 7, 8, 9) x -= 5 

I cannot find an equivalent method on a MutableList .

+6
source share
2 answers

MutableList missing -= and --= because it does not extend the Shrinkable . Various motivations for this can be found here.

MutableList has diff , filter and other methods that can help you if you are in a situation where reassigning a variable (or creating a new variable) can be an option, and performance isn 't paramount:

 var mylist = MutableList(1, 2, 3) mylist = mylist diff Seq(1) val myNewList = mylist.filter(_ != 2) val indexFiltered = mylist.zipWithIndex.collect { case (el, ind) if ind != 1 => el } 

You can often use a ListBuffer instead of a MutableList , which unlocks the necessary methods -= and --= :

 val mylist = ListBuffer(1, 2, 3) mylist -= 1 //mylist is now ListBuffer(2, 3) mylist --= Seq(2, 3) //mylist is now empty 
+8
source

This is not an answer, just to warn you of problems (at least in 2.11.x):

 //street magic scala> val a = mutable.MutableList(1,2,3) a: scala.collection.mutable.MutableList[Int] = MutableList(1, 2, 3) scala> a += 4 res7: a.type = MutableList(1, 2, 3, 4) scala> a res8: scala.collection.mutable.MutableList[Int] = MutableList(1, 2, 3, 4) scala> a ++= List(8,9,10) res9: a.type = MutableList(1, 2, 3, 4, 8, 9, 10) scala> val b = a.tail b: scala.collection.mutable.MutableList[Int] = MutableList(2, 3, 4, 8, 9, 10) scala> b.length res10: Int = 6 scala> a.length res11: Int = 7 scala> a ++= List(8,9,10) res12: a.type = MutableList(1, 2, 3, 4, 8, 9, 10, 8, 9, 10) scala> b += 7 res13: b.type = MutableList(2, 3, 4, 8, 9, 10, 7) scala> a res14: scala.collection.mutable.MutableList[Int] = MutableList(1, 2, 3, 4, 8, 9, 10, 7) scala> b res15: scala.collection.mutable.MutableList[Int] = MutableList(2, 3, 4, 8, 9, 10, 7) scala> a ++= List(8,9,10) res16: a.type = MutableList(1, 2, 3, 4, 8, 9, 10, 7) 

This example is taken from some gist - I posted it on facebook with # devid_blein #street_magic tags, but I can not find the original link on the Internet.

+1
source

All Articles