Reputation: 318
I have two ArrayBuffers, the first (A
) is a subset of the other and only contains long IDs. The second (B
) contains objects of a case class g
which has the ID as an attribute. Now I want to loop over A
in order to remove all objects in B
matching the corresponding ID as well as the ID from A
. I use the following method
def removeID (ID:Long) {
B.find(_.ID == ID) match {
case Some(s) =>
B.remove(B.indexWhere(_.ID == ID))
A -= ID
case None => sys.error("Cannot remove ID $ID")
}
}
I'm a little bit confused since the error I get now is:
java.lang.RuntimeException: Cannot remove ID 0
which does not make sense since there is no 0 in A
or B
. I tried to figure out what exactly happens during the loop it is obvious that
for(ID <- A) {removeID(ID)}
just applies the removeID
method on every 2nd element until it reaches the end of A
and then tries to find the ID 0
which does not exists.
Does somebody know where this behavior comes from?
Edit: So the problem is not the removal of an ID (it happens like it should) but rather the iteration over the ArrayBuffer which does not make sense.
Upvotes: 0
Views: 308
Reputation: 8139
You probably get that error because there is no ID 0. So the case None
part gets executed.
But I suggest you use filter instead.
def removeID(ID: Long) {
B = B.filterNot(_.ID == ID)
A -= ID
}
Upvotes: 0