Scala FAQ: Can you share some examples of how to implement break and continue functionality in Scala?
Introduction
Sure. The example Scala code below shows both a break and a continue example. As you can see from the import
statement, it uses the code in the Scala util.control.Breaks
package.
To understand how this works, let's first look at the code, and then the output.
First, here's the code:
package com.alvinalexander.breakandcontinue import util.control.Breaks._ object BreakAndContinueDemo extends App { // 1) BREAK: this example breaks out of the for loop when (i > 4) println("\n=== BREAK EXAMPLE ===") breakable { for (i <- 1 to 10) { println(i) if (i > 4) break // break out of the for loop } } // 2) CONTINUE: this example acts like a Java continue statement // "A continue statement skips the current iteration of a for, while , or do-while loop." println("\n=== CONTINUE EXAMPLE ===") val searchMe = "peter piper picked a peck of pickled peppers" var numPs = 0 for (i <- 0 until searchMe.length) { breakable { if (searchMe.charAt(i) != 'p') { break // break out of the 'breakable', continue the outside loop } else { numPs += 1 } } } println("Found " + numPs + " p's in the string.") }
Here's the output from the code:
=== BREAK EXAMPLE === 1 2 3 4 5 === CONTINUE EXAMPLE === Found 9 p's in the string.
To understand how this code works, let's break it down a little bit.
The break example
The Scala break example is pretty easy to reason about. Again, here's the code:
breakable { for (i <- 1 to 10) { println(i) if (i > 4) break // break out of the for loop } } // more code here ...
In this case, when i
becomes greater than 4
, the break
word (a method, actually) is reached. At this point an exception is thrown, and the for
loop is exited. The breakable
word (also a method) catches the exception, and the code continues with anything else that might be after the breakable
block.
The continue example
If you read the explanation for the break
example, you should be able to reason about how the continue
example works. First, here's the code:
val searchMe = "peter piper picked a peck of pickled peppers" var numPs = 0 for (i <- 0 until searchMe.length) { breakable { if (searchMe.charAt(i) != 'p') { break // break out of the 'breakable', continue the outside loop } else { numPs += 1 } } } println("Found " + numPs + " p's in the string.")
Following the earlier explanation, as we walk through the characters in the String variable named searchMe
, if the current character is not the letter p
, we break out of the if/then statement, and the loop continues executing.
What really happens here is that the break
keyword is reached, an exception is thrown, and that exception is caught by breakable
. The exception serves to get us out of the if/then statement, and catching it allows the loop to continue executing with the next element.
About that continue example
I know that continue
example is pretty lame, but it's all I could come up with. It's a variation of the Java continue example at http://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html.
If you know Scala, you know that there are much better ways to write this example in Scala. A direct solution is to use the count
method:
val count = searchMe.count(_ == 'p')
When this code is run, count
will be 9
.
Another 'continue' example
While testing the “continue” approach, I just came up with the following example, which prints the numbers "1,3,5,7,9":
import util.control.Breaks._ object BreakTests extends App { for (i <- 1 to 10) { breakable { if (i % 2 == 0) break println(i) } } }
Hopefully seeing that simpler example will also be helpful.
Scala breakable and break - A little more information
If you dig into the source code for the util.control.Breaks package, you'll see that breakable
is defined like this:
def breakable(op: => Unit) { try { op } catch { case ex: BreakControl => if (ex ne breakException) throw ex } }
You'll also see that break
is defined like this:
def break(): Nothing = { throw breakException }
I encourage you to dig into that source code to learn a little more about how this works.
Summary
If you needed to see some Scala break and continue examples, I hope this tutorial has been helpful.