Go to the start of the for loop in Scala

In the for loop in my Scala code, I want to go to the beginning of the loop and not follow the instructions below if the particular condition is true. In Java, I can use "continue" for this. But "continue" does not work in Scala. So, how can I go to the beginning of my cycle in a Scala program?

Please help Thanks.

+3
source share
2 answers

If you are using Scala 2.7, http://www.scala-lang.org/node/257

Scala 2.7 -. - . , if. Scala 2.8 , .

Scala 2.8

import util.control.Breaks._
// for continue, write this somewhere in your program
val continue = new Breaks
/* use like */
Breaks.breakable {
  for (i <- 1 to 10)
  continue.breakable { if (i % 2 == 0) continue.break; println(i); if (i == 7) Breaks.break }
}


//source http://daily-scala.blogspot.com/2010/04/breaks.html

, break continue , , Scala.

+5

-, , , (, xs.map(doSomeStuff).filter(condition).foreach(doConditionalStuff)). , , . , , : , .

continue - . : , , , . - : map, , continue ?

, , Scala ( , ) breakable, , :

import scala.util.control.Breaks._
breakable {
  for (i <- 1 to 10) {
    if (i>3) break
    println(i)
  }
}

, for:

import scala.util.control.Breaks._
for (i <- 1 to 10) {
  breakable {
    if ((i%2)==0) break
    println(i)
  }
}

, break. for :

val outer,inner = new scala.util.control.Breaks
outer.breakable {
  for (i <- 1 to 10) {
    inner.breakable {
      if ((i%2)==0) inner.break
      if (i>3) outer.break
      println(i)
    }
  }
}

, , :

// Do this once at the top of the file
import scala.util.control.Breaks._
object Continued extends scala.util.control.Breaks {}
import Continued.{break=>continue, breakable=>continuing}

// Now every time you need it:
breakable{ for (i <- 1 to 10) continuing {
  if ((i%2)==0) continue
  if (i>3) break
  println(i)
}}

, , , , Scala , .

+7

All Articles