How do I break out a loop?
var largest=0
for(i<-999 to 1 by -1) {
for (j<-i to 1 by -1) {
val product=i*j
if (largest>product)
// I want to break out here
else
if(product.toString.equals(product.toString.reverse))
largest=largest max product
}
}
How do I turn nested for loops into tail recursion?
From Scala Talk at FOSDEM 2009 http://www.slideshare.net/Odersky/fosdem-2009-1013261 on the 22nd page:
Break and continue Scala does not have them. Why? They are a bit imperative; better use many smaller functions Issue how to interact with closures. They are not needed!
What is the explanation?
Basic method to break the loop, using Breaks class. By declaring the loop as breakable.
It is never a good idea to break out of a for-loop. If you are using a for-loop it means that you know how many times you want to iterate. Use a while-loop with 2 conditions.
for example
Simply We can do in scala is
output :
Since there is no
break
in Scala yet, you could try to solve this problem with using areturn
-statement. Therefore you need to put your inner loop into a function, otherwise the return would skip the whole loop.Scala 2.8 however includes a way to break
http://www.scala-lang.org/api/rc/scala/util/control/Breaks.html
use Break module http://www.tutorialspoint.com/scala/scala_break_statement.htm
The third-party
breakable
package is one possible alternativehttps://github.com/erikerlandson/breakable
Example code: