
- Scala - Home
- Scala - Overview
- Scala - Features
- Scala - Environment Setup
- Scala - Build Tool (SBT)
- Scala - REPL
- Scala - Dot & Dotty
- Scala - Basic Syntax
- Scala - Hello World Program
- Scala - Identifiers
- Scala - Keywords
- Scala - Comments
- Scala - Code Blocks
- Scala - Semicolon
- Scala - Constructs
- Scala - Expressions
- Scala - Input and Output
- Scala - Optional Braces
- Scala - Underscore (_)
- Data Types and Variables
- Scala - Data Types
- Scala - Type Bounds
- Scala - Context Bound
- Scala - Variances
- Scala - Type Hierarchy
- Scala - Variables
- Scala - Variable Scopes
- Scala - Literals
- Scala - Numeric Types
- Scala - Boolean Types
- Scala - Char Type
- Scala - Unit Types
- Scala - Strings
- Scala - Arrays
- Scala - Null Type
- Scala - Nothing
- Scala - Any Type
- Scala - AnyRef Type
- Scala - Unified Types
- Scala - Dates and Times
- Scala - Ranges
- Scala - Multidimensional Arrays
- Scala - WrappedArray
- Scala - StringBuilder
- Scala - String Interpolation
- Scala - StringContext
- Scala - Type Casting
- Scala var vs val
- Scala Operators
- Scala - Operators
- Scala - Rules for Operators
- Scala - Arithmetic Operators
- Scala - Relational Operators
- Scala - Logical Operators
- Scala - Bitwise Operators
- Scala - Assignment Operators
- Scala - Operators Precedence
- Scala - Symbolic Operators
- Scala - Range Operator
- Scala - String Concatenation Operator
- Scala Conditional Statements
- Scala - IF ELSE
- Scala - IF-ELSE-IF-ELSE Statement
- Scala - Nested IF-ELSE Statement
- Scala Loop Statements
- Scala - Loop Statements
- Scala - while Loop
- Scala - do-while Loop
- Scala - Nested Loops
- Scala - for Loop
- Scala - break Statement
- Scala - yield Keyword
- Scala Classes & Objects
- Scala - Classes & Objects
- Scala - Constructors
- Scala - Auxiliary Constructor
- Scala - Primary Constructor
- Scala - This Keyword
- Scala - Nested Classes
- Scala - Getters and Setters
- Scala - Object Private Fields
- Scala - Singleton Object
- Scala - Companion Objects
- Scala - Creating Executable Programs
- Scala - Stateful Object
- Scala - Enumerations
- Scala - Polymorphism
- Scala - Access Modifiers
- Scala - Apply Method
- Scala - Update Methods
- Scala - UnapplySeq Method
- Scala - Inheritance
- Scala - Extending a Class
- Scala - Method Overloading
- Scala - Method Overriding
- Scala - Generic Classes
- Scala - Generic Functions
- Scala - Superclass Construction
- Scala Methods & Functions
- Scala - Functions
- Scala - Main Methods
- Scala - Functions Call-by-Name
- Scala - Functions with Named Arguments
- Scala - Function with Variable Arguments
- Scala - Recursion Functions
- Scala - Default Parameter Values
- Scala - Functions without Parameters
- Scala - Implicit Parameters
- Scala - Higher-Order Functions
- Scala - Nested Functions
- Scala - Extension Methods
- Scala - Anonymous Functions
- Partially Applied Functions
- Scala - Lazy Val
- Scala - Pure Function
- Scala - Currying Functions
- Scala - Control Abstractions
- Scala - Corecursion
- Scala - Unfold
- Scala - Tail Recursion
- Scala - Infinite Sequences
- Scala - Dynamic Invocation
- Scala - Lambda Expressions
- Scala Collections
- Scala - Collections
- Mutable and Immutable Collections
- Scala - Lists
- Scala - Sets
- Scala - Maps
- Scala - TreeMap
- Scala - SortedMap
- Scala - Tuples
- Scala - Iterators
- Scala - Options
- Scala - Infinite Streams
- Scala - Parallel Collections
- Scala - Algebraic Data Types
- Scala Pattern Matching
- Scala - Pattern Matching
- Scala - Type Patterns
- Scala - Exception Handling
- Scala - Extractors
- Scala - Regular Expressions
- Scala Files I/O
- Scala - Files I/O
- Scala Advanced Concepts
- Scala - Closures
- Scala - Futures
- Scala - Promises
- Scala - Traits
- Scala - Trait Mixins
- Scala - Layered Traits
- Scala - Trait Linearization
- Scala - Sealed Traits
- Scala - Transparent Traits
- Scala - Literal Type Arithmetic
- Scala - Inline keyword
- Scala - Def, Var & Val
- Scala - Dropped Features
- Scala - BDD Testing
Scala - break Statement
The break statement in Scala is used to terminate the loop immediately. While Scala does not have a built-in break keyword like some other languages. But you can achieve similar functionality using the Breaks class provided in scala.util.control package.
Syntax
Following is the syntax to use break statement −
import scala.util.control.Breaks. breakable { for (var x <- Range) { if (condition) { break // terminate the loop } statement(s) } }
Example of Scala break Statement
Try the following example program to understand loop with break −
import scala.util.control.Breaks._ object Demo { def main(args: Array[String]) { var a = 0; // for loop execution with a range and break logic breakable { for (a <- 1 to 10) { if (a == 5) { break // terminate the loop } println("Value of a: " + a) } } } }
The above code shows how to use break within a for loop to terminate it when a = 5.
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
Command
>scalac Demo.scala >scala Demo
Output
Value of a: 1 Value of a: 2 Value of a: 3 Value of a: 4
In the example above, the loop terminates when a is 5, after reaching the break statement.
Breaking Nested Loops
Existing break has an issue while using for nested loops. Just in case to use break for nested loops, follow this method. This is an example program for breaking nested loops.
Example
import scala.util.control.Breaks._ object NestedBreakDemo { def main(args: Array[String]) = { breakable { for (i <- 1 to 3) { for (j <- 1 to 3) { if (i == 2 && j == 2) { break // terminate the outer loop } println(s"i = $i, j = $j") } } } } }
Save the above program in NestedBreakDemo.scala. The following commands are used to compile and execute this program.
Command
\>scalac NestedBreakDemo.scala \>scala NestedBreakDemo
Output
i = 1, j = 1 i = 1, j = 2 i = 1, j = 3 i = 2, j = 1
In this example, the break statement terminates the outer loop when both i and j are equal to 2.
Conditional Break in for Loop
The break statement can also be used within the conditional statement to break a for loop.
Example
In the following example, we are using break inside the conditional statement −
import scala.util.control.Breaks._ object ConditionalBreakDemo { def main(args: Array[String]) = { breakable { for (a <- 1 to 10) { if (a % 2 == 0) { break // terminate the loop when a is even } println("Value of a: " + a) } } } }
Save the above program in ConditionalBreakDemo.scala. The following commands are used to compile and execute this program.
Command
\>scalac ConditionalBreakDemo.scala \>scala ConditionalBreakDemo
Output
Value of a: 1
In this example, the for loop terminates as soon as it encounters an even number.
Alternatives to Using break
In Scala, there are various alternatives to using the break statement. Here are a few −
1. Using Return from a Function
You can use return to exit from the loop by encapsulating the loop inside a function.
object ReturnBreakDemo { def main(args: Array[String]) = { def loopWithReturn(): Unit = { for (a <- 1 to 10) { if (a == 5) { return // terminate the loop } println("Value of a: " + a) } } loopWithReturn() } }
In above example, loop is placed inside a function. The return is used to exit the function. So effectively breaking the loop.
Save the above program in ReturnBreakDemo.scala. The following commands are used to compile and execute this program.
Command
\>scalac ReturnBreakDemo.scala \>scala ReturnBreakDemo
Output
Value of a: 1 Value of a: 2 Value of a: 3 Value of a: 4
2. Using Boolean Flag
A boolean flag can be used to control the loop execution.
object BooleanFlagBreakDemo { def main(args: Array[String]) = { var shouldBreak = false for (a <- 1 to 10 if !shouldBreak) { if (a == 5) { shouldBreak = true // set flag to terminate the loop } else { println("Value of a: " + a) } } } }
In above example, a boolean flag (shouldBreak) is used to control the loop execution. When the flag is set to true, the loop terminates.
Save the above program in BooleanFlagBreakDemo.scala. The following commands are used to compile and execute this program.
Command
\>scalac BooleanFlagBreakDemo.scala \>scala BooleanFlagBreakDemo
Output
Value of a: 1 Value of a: 2 Value of a: 3 Value of a: 4
Using Higher-Order Functions
Scala collection library has higher-order functions like takeWhile to control loop execution.
object HigherOrderFunctionDemo { def main(args: Array[String]) = { (1 to 10).takeWhile(_ != 5).foreach(a => println("Value of a: " + a)) } }
The takeWhile function processes elements until the condition (_ != 5) is met. So terminates the loop when the condition is false.
Save the above program in HigherOrderFunction Demo.scala. The following commands are used to compile and execute this program.
Command
\>scalac HigherOrderFunctionDemo.scala \>scala HigherOrderFunctionDemo
Output
Value of a: 1 Value of a: 2 Value of a: 3 Value of a: 4