Scala, give me a break :)

I have been recently asked whether it is possible to use break (and continue as well) in a loop with Scala and it occurred to me that I have never come across such a case. Coming from Java, I do know how to employ break and continue in a while loop, for example, so why would it be different in Scala, considering that it is builds on top of the JVM? It is actually a bit more complicated than that. Although Scala does not specifically have the keywords break and continue, it does offer similar functionality through scala.util.control.Breaks.

Here is an example of how to use break from the Class Breaks, as follows:

import scala.util.control.Breaks._
import java.io._

val in = new BufferReader(new InputStreamReader(System.in))

breakable {
  while (true) {
    println ("? ")
    if (input.readLine() == "") break
  }
}

In Java, the above would corresponding to this:

BufferedReader in =
   new BufferedReader(new InputStreamReader(System.in));
   while (true) {
     if (in.readLine() == "") break
   }

The breakable function has become available from Scala 2.8 onwards and before that we would have tacked the issues mostly through 2 approaches:

  • by adding a boolean variable indicating whether the loops keeps being valid;
  • by re-writing the loop as a  recursive function;

Happy Scala programming 🙂

 

Posted on June 16, 2018, in Uncategorized. Bookmark the permalink. Leave a comment.

This site uses Akismet to reduce spam. Learn how your comment data is processed.