Reputation: 5614
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
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
Reputation: 12446
You can use one of the 2 options:
foo
variable to filter undesired resultsvar foo = true
for (i <- 0 to 9 if foo) {
doSomething()
if (<want to break?>) foo = false
}
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
Reputation: 1288
val foo: Boolean = true
for{
i <- 0 until 10
if foo
} doSomething()
Upvotes: 2