break and continue (scala.util.control.Breaks)
In this page:
break and continue (scala.util.control.Breaks)
Scala has no built-in break or continue keywords, since early loop exits go against its functional style, but scala.util.control.Breaks provides a break() function usable inside a breakable { ... } block for early exit. There is no direct equivalent of continue in Scala at all -- idiomatic code restructures the loop body with an if guard instead of trying to skip an iteration. Breaks is considered an escape hatch, not idiomatic day-to-day Scala.
Warning: Scala has no continue equivalent -- use an if-guard inside the loop body to skip processing for specific values instead.
Example: break and continue (scala.util.control.Breaks)
import scala.util.control.Breaks._
object Main extends App {
breakable {
for (i <- 1 to 10) {
if (i > 5) break()
println(s"Value: $i")
}
}
// No continue keyword -- use an if-guard to skip instead
for (i <- 1 to 6) {
if (i % 2 != 0) {
println(s"Odd: $i")
}
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: