3

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?

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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

2 Comments

Great :-) don't hesitate to flag one of the answers you found relevant has accepted :-) (if both were, you can pick at random it's all fine :-) )
Thanks :) I'll also come back when I am able to vote, to upvote both answers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.