I have some Scala code from a game that is intended to call the onInteract(gameData: GameData, player: Player)
method on each instance of a GameObject
in a mutable.ArrayBuffer
, gameobjects
. However, sometimes these GameObject
s will remove themselves from the ArrayBuffer
, using the code gameobjects -= this
. Since this alters the ArrayBuffer
, Scala throws a NullPointerException
. The code could be considered similar to the following:
for (gameobject <- gameobjects) {
if (/* some condition */) gameobjects -= gameobject
}
and would throw an exception whenever an object is removed.
How can I remedy this? I'd imagine an ArrayBuffer
, or at least the for
loop, is unsuitable here.