3.5. Implementing break and continue
Problem
You have a situation where you need to use a break
or continue
construct, but Scala doesn’t have
break
or continue
keywords.
Solution
It’s true that Scala doesn’t have break
and continue
keywords, but it does offer similar
functionality through scala.util.control.Breaks
.
The following code demonstrates the Scala “break” and “continue” approach:
package
com.alvinalexander.breakandcontinue
import
util.control.Breaks._
object
BreakAndContinueDemo
extends
App
{
println
(
"\n=== BREAK EXAMPLE ==="
)
breakable
{
for
(
i
<-
1
to
10
)
{
println
(
i
)
if
(
i
>
4
)
break
// break out of the for 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.
(The “pickled peppers” example comes from a continue
example in the Java documentation.
More on this at the end of the recipe.)
The following discussions describe how this code works.
The break example
The 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
}
}
In this case, when i
becomes
greater than 4
, the break ...
Get Scala Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.