Powered By Blogger

Thursday, September 15, 2011

Loop Break - Scala

Following example shows how to break out of a loop in Scala. Here the package, 'util.control.Breaks._' is imported and the foreach loop is enclosed in a 'breakable' block (to avoid a runtime exception caused by the break). In the example the loops breaks when n is 5.

======================================================

package shyarmal.test.scala

import util.control.Breaks._

object ScalaBreak {

  def main(args: Array[String]) {

    val nums = 1 :: 2 :: 3 :: 4 :: 5 :: 6 :: 7 :: Nil
    breakable {
      nums.foreach(n => {
        if (n == 5)
          break
        println(n)
      })
    }

  }
}

======================================================

The output: 1 2 3 4

thanks,
Shyarmal

No comments:

Post a Comment