August 2013
Intermediate to advanced
720 pages
16h 23m
English
You have a situation where you need to use a break or continue construct, but Scala doesn’t have
break or continue keywords.
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:
packagecom.alvinalexander.breakandcontinueimportutil.control.Breaks._objectBreakAndContinueDemoextendsApp{println("\n=== BREAK EXAMPLE ===")breakable{for(i<-1to10){println(i)if(i>4)break// break out of the for loop}}println("\n=== CONTINUE EXAMPLE ===")valsearchMe="peter piper picked a peck of pickled peppers"varnumPs=0for(i<-0untilsearchMe.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 is pretty easy to reason about. Again, here’s the code:
breakable{for(i<-1to10){println(i)if(i>4)break// break out of the for loop}}
In this case, when i becomes
greater than 4, the break ...
Read now
Unlock full access