Scala Break statement

 244 total views,  2 views today

Welcome to Scala series. In this tutorial, you will learn about Scala break statement.

Break statement is common in most of the programming languages.It is essentially used to break the loop of execution. The flow of action comes out of the loop once the break statement is executed.

If there are nested loops, then break statement will terminate the inner loop where break statement has been applied.

Break statement is available by default in Java.But in Scala, to use a break statement , we have to import a package.

import scala.util.control.Breaks._

But, this not enough, break statement will throw exception. To avoid that, we have enclose the loop in a breakable block.

Let use see a few examples

Break statement in for loop

import scala.util.control.Breaks._

object StaticReference {
  def main(args: Array[String]): Unit = {
    var i = 0;
    breakable {

      for (i <- 1 to 10) {

        if (i == 3) {
          break
        }
        println(i)
      }
    }
  }
}

Output

0
1

Break statement in while loop

import scala.util.control.Breaks._

object StaticReference {
  def main(args: Array[String]): Unit = {
    var i = 0;
    breakable {

      while (i < 5) { //while condition

        if (i == 3) {
          break // break
        }
        println(i)
        i = i + 1; // incrementing
      }
    }
  }
}

Output

0
1
2

References : https://docs.scala-lang.org/tour/tour-of-scala.html

Tags :

About the Author

Rajasekar

Hey There, My name is Rajasekar and I am the author of this site. I hope you are liking my tutorials and references. Programming and learning new technologies are my passion. The ultimate idea of this site is to share my knowledge(I am still a learner :)) and help you out!. Please spread your words about us (staticreference.com) and give a thumbs up :) Feel free to contact me for any queries!.