← Back to Scala Course | Chapter 4: Control Flow | Lesson 6 of 7

break and continue (scala.util.control.Breaks)

Scala has no simple break or continue commands, so it borrows a special helper to leave a loop early. It is like needing a special pass to leave class before the bell.
Syntax
scala
import scala.util.control.Breaks._

breakable {
  for (item <- collection) {
    if (condition) break
    // body
  }
}

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)

markup
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")
    }
  }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using break without wrapping the loop in breakable { ... }, which throws an exception instead of exiting.
  2. Looking for a continue keyword, which does not exist; the breakable block goes inside the loop body to skip an iteration.
  3. Forgetting import scala.util.control.Breaks._, so break() and breakable are not found.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.