Busti
Busti

Reputation: 5614

Multiple statements in for-loops

In java you can do something like this:

 Boolean foo = true;
 for(int i=0; i<10 && foo; i++) {
     doSomething();
 }

Is it also possible in Scala?

Upvotes: 1

Views: 992

Answers (3)

Azzie
Azzie

Reputation: 366

possible but not the best practice. Do you want to continue with next record if foo == false or break? Does doSomething modify foo? Take a look at fold and forall in scala api

 for (i <- 1 to 10 if foo) { doSomething() }

Upvotes: 3

Eugene Loy
Eugene Loy

Reputation: 12446

You can use one of the 2 options:

  1. use your foo variable to filter undesired results

var foo = true
for (i <- 0 to 9 if foo) {
    doSomething()
    if (<want to break?>) foo = false
}
  1. use break:

import scala.util.control.Breaks._

breakable {
    for (i <- 0 to 9) {
        doSomething()
        if (<want to break?>) break
    }
}

... though I generally suggest to shape your algorithms in more FP-ish/Scala way and avoid having mutable state or cycles (and breaks in them) when possible.

Upvotes: 2

Mariusz Nosiński
Mariusz Nosiński

Reputation: 1288

val foo: Boolean = true
for{
  i <- 0 until 10
  if foo
} doSomething()

Upvotes: 2

Related Questions