how should one deal w/ removing something from a l...
# announcements
t
how should one deal w/ removing something from a list while your are in the middle of
forEach{}
over it? Does it explode, or what?
💥 1
b
if you delete in middle of
forEach{}
it will Concurrent method exception. So use Iterator for do that type of work.
e
MutableList.listIterator()
returns a
MutableListIterator
you can use `for`/`forEach` on an iterator directly too
(
.iterator()
also works in the above example, returning a
MutableIterator
, but
MutableListIterator
has some additional methods such as
.add()
and
.set()
)
a
Is there any reason for not applying filter first and then doing forEach?
t
@Ashish Kumar Joy it's not realistic. Neither is the iterator (I don't think.. maybe?). It's for message dispatch. It's a list of function that want to be called when a specific message arrives over the network. Sometimes the functions want to remove themselves from interest in that message before the next one is dispatched.
the functions don't know they are part of a
forEach
loop. they just don't want to be called again. but they figure that out while they are being dispatched too.
when I've done this in the past it'd just copy the list and loop over that... they the original list changed be changed no problem. I'm just wondering if there is a better way in kotlin.
@ephemient yeah. that'd work. I can have the functions return false if they want out, and use the iterator pattern to remove them.
n
set a state in the list item, and then clean up after the loop (
list.removeAll { it.dont_call_me_again }
)
1