Home > database >  How to skip an iteration in a for-loop in Scala?
How to skip an iteration in a for-loop in Scala?

Time:10-07

For example in C you would be able to write

for (int i = 0; i < 10 ; i  ) {
  if (i == 2) i  = 1
  // do stuff
}

Since Scala uses ranges, how would we modify the iterator?

CodePudding user response:

You would have multiple solutions, but basically using a .filter() like clause somewhere should do it.

Like (0 to 10).filterNot(_ == 3).foreach(doStuff()) for example

CodePudding user response:

You can use a guard:

for (i <- 0 to 10; if i != 2) println(i)

This would print the numbers from 0 to 10, excluding 2.

You can see this code in action an play around with it here on Scastie.

  • Related