Provides thebreak control abstraction.
Thebreak method uses aControlThrowable to transfer control up the stack to an enclosingbreakable.
It is typically used to abruptly terminate afor loop, but can be used to return from an arbitrary computation.
Control resumes after thebreakable.
If there is no matchingbreakable, theBreakControl thrown bybreak is handled in the usual way: if not caught, it may terminate the currentThread.
BreakControl carries no stack trace, so the default exception handler does not print useful diagnostic information; there is no compile-time warning if there is no matchingbreakable.
A catch clause usingNonFatal is safe to use withbreak; it will not short-circuit the transfer of control to the enclosingbreakable.
Abreakable matches a call tobreak if the methods were invoked on the same receiver object, which may be the convenience valueBreaks.
Example usage:
val mybreaks = new Breaksimport mybreaks.{break, breakable}breakable { for (x <- xs) { if (done) break() f(x) }}Calls tobreak from one instance ofBreaks will never resume at thebreakable of some other instance.
Any intervening exception handlers should useNonFatal, or useTry for evaluation:
val mybreaks = new Breaksimport mybreaks.{break, breakable}breakable { for (x <- xs) Try { if (quit) break else f(x) }.foreach(println)}Break from the dynamically closest enclosing breakable block that also uses thisBreaks instance.
Break from the dynamically closest enclosing breakable block that also uses thisBreaks instance.
This might be different from the statically closest enclosing block!
Invocation without parentheses relies on the conversion to "empty application".
A block from which one can exit with abreak.
A block from which one can exit with abreak. Thebreak may be executed further down in the call stack provided that it is called on the exact same instance ofBreaks.
Try a computation that produces a value, supplying a default to be used if the computation terminates with abreak.
Try a computation that produces a value, supplying a default to be used if the computation terminates with abreak.
tryBreakable { (1 to 3).map(i => if (math.random < .5) break else i * 2)} catchBreak { Vector.empty}