Where is Scala’s “break” Keyword?

Does Scala have the break keyword?

The short answer is “No”. Scala doesn’t support break and continue at the language level. However it provides you with the right API calls to achieve the same results.

If you check the Scala API, you’ll see that scala.util.control package contains a class called Breaks. You need to use the breakable() and break() methods of this class in order to break out of a loop. Have a look at the following code snippet:

import util.control.Breaks.{break, breakable}

breakable {
  for (i <- 1 to 10) {
    if (i < 4)
      println(i)
    else
      break
  }
}

The above code contains a for loop with a single generator. The loop is broken when i is 4. Until then it prints the index value.

As you can see, by using breakable() and break() you can break out of a loop. However, arguably, by using other language features and by applying a more functional thinking, you may never need the break keyword. For example, the same output can be obtained by adding a guard after the generator.

for {
  i <- 1 to 10
  if i < 4
} println(i)

//or

for (i <- 1 to 10 if i < 4 ) {
  println(i)
}

This is more elegant, shorter and more readable.

, ,

  1. Leave a comment

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: