Chris
Chris

Reputation: 233

How can I minimize these similar if statements in scala?

I have an array in scala:

  var walls: Array[LineSprite] = new Array[LineSprite](26)

And then I have these if statements:

if(curPlayer.intersects(walls(0))) {
handleCollision
updateLives(-1)
}
if(curPlayer.intersects(walls(1))) {
handleCollision
updateLives(-1)
}
if(curPlayer.intersects(walls(2))) {
handleCollision
updateLives(-1)
}
if(curPlayer.intersects(walls(3))) {
handleCollision
updateLives(-1)
}
if(curPlayer.intersects(walls(4))) {
handleCollision
updateLives(-1)
}
if(curPlayer.intersects(walls(5))) {
handleCollision
updateLives(-1)
}
if(curPlayer.intersects(walls(6))) {
handleCollision
updateLives(-1)
}
if(curPlayer.intersects(walls(7))) {
handleCollision
updateLives(-1)
}
if(curPlayer.intersects(walls(8))) {
handleCollision
updateLives(-1)
}
if(curPlayer.intersects(walls(9))) {
handleCollision
updateLives(-1)
}
if(curPlayer.intersects(walls(10))) {
handleCollision
updateLives(-1)
}
if(curPlayer.intersects(walls(11))) {
handleCollision
updateLives(-1)
}

...

How can I, instead of having a separate if statement for each item in the array that calls handleCollision and updateLives(-1), make it so that I can only have one if statement for all the items in the array?

Thank you.

Upvotes: 1

Views: 158

Answers (1)

4lex1v
4lex1v

Reputation: 21557

I think this should solve you problem

walls.foreach(w => if (curPlayer.intersects(w)) {
  handleCollision
  updateLives(-1)
})

I you want you can also use shorter solution with underscore

walls.foreach(if (curPlayer.intersects(_)) {...})

It wont give you anything but a more concise syntax

Upvotes: 3

Related Questions