M.Ahsen Taqi
M.Ahsen Taqi

Reputation: 965

Removing an element from 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 method to remove element from ListBuffer like this:

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

I am unable to find an equivalent method on MutableList.

Upvotes: 8

Views: 5887

Answers (2)

dk14
dk14

Reputation: 22374

It's not the answer, just to warn you about 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've posted it on facebook with #devid_blein #street_magic tags, but can't find original link on the internet.

Upvotes: 1

Ben Reich
Ben Reich

Reputation: 16324

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

MutableList does have diff, filter, and other methods which can help you in case you are in a situation where reassigning a variable (or instantiating a new variable) might be an option, and performance concerns aren'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 ListBuffer instead of MutableList, which will unlock the desired -= and --= methods:

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

Upvotes: 9

Related Questions