
- 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 - for Loop
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times. There are various forms of for loop in Scala which are described below −
Syntax for loop with ranges
The simplest syntax of for loop with ranges in Scala is −
for( var x <- Range ){ statement(s); }
Here, the Range could be a range of numbers and that is represented as i to j or sometime like i until j. The left-arrow <- operator is called a generator, so named because it's generating individual values from a range.
Example of Scala for Loop
Try the following example program to understand loop control statements (for statement) in Scala Programming Language:
object Demo { def main(args: Array[String]) { var a = 0; // for loop execution with a range for( a <- 1 to 10){ println( "Value of a: " + a ); } } }
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 value of a: 5 value of a: 6 value of a: 7 value of a: 8 value of a: 9 value of a: 10
Scala for Loop with Until
Try the following example program to understand loop control statements (for statement) to print loop with the range i until j in Scala Programming Language.
object Demo { def main(args: Array[String]) { var a = 0; // for loop execution with a range for( a <- 1 until 10){ println( "Value of a: " + a ); } } }
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 value of a: 5 value of a: 6 value of a: 7 value of a: 8 value of a: 9
Scala for Loop with Multiple Ranges
You can use multiple ranges separated by semicolon (;) within for loop and in that case, loop will iterate through all the possible computations of the given ranges. Following is an example of using just two ranges, you can use more than two ranges as well.
object Demo { def main(args: Array[String]) { var a = 0; var b = 0; // for loop execution with a range for( a <- 1 to 3; b <- 1 to 3){ println( "Value of a: " + a ); println( "Value of b: " + b ); } } }
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 b: 1 Value of a: 1 Value of b: 2 Value of a: 1 Value of b: 3 Value of a: 2 Value of b: 1 Value of a: 2 Value of b: 2 Value of a: 2 Value of b: 3 Value of a: 3 Value of b: 1 Value of a: 3 Value of b: 2 Value of a: 3 Value of b: 3
Scala for Loop with Collections
You can use for loop to iterate collections.
Syntax
for( var x <- List ){ statement(s); }
Here, the List variable is a collection type having a list of elements and for loop iterate through all the elements returning one element in x variable at a time.
Example
object Demo { def main(args: Array[String]) { var a = 0; val numList = List(1,2,3,4,5,6); // for loop execution with a collection for( a <- numList ){ println( "Value of a: " + a ); } } }
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 value of a: 5 value of a: 6
Scala for Loop with Filters
Scala's for loop allows to filter out some elements using one or more if statement(s). Following is the syntax of for loop along with filters. To add more than one filter to a 'for' expression, separate the filters with semicolons(;).
for( var x <- List if condition1; if condition2... ){ statement(s); }
Example
object Demo { def main(args: Array[String]) { var a = 0; val numList = List(1,2,3,4,5,6,7,8,9,10); // for loop execution with multiple filters for( a <- numList if a != 3; if a < 8 ){ println( "Value of a: " + a ); } } }
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: 4 value of a: 5 value of a: 6 value of a: 7
Scala for Loop with Yield
You can store return values from a "for" loop in a variable or can return through a function. To do so, you prefix the body of the 'for' expression by the keyword yield. The following is the syntax.
var retVal = for{ var x <- List if condition1; if condition2... } yield x
Note the curly braces have been used to keep the variables and conditions and retVal is a variable where all the values of x will be stored in the form of collection.
Example
object Demo { def main(args: Array[String]) { var a = 0; val numList = List(1,2,3,4,5,6,7,8,9,10); // for loop execution with a yield var retVal = for{ a <- numList if a != 3; if a < 8 }yield a // Now print returned values using another loop. for( a <- retVal){ println( "Value of a: " + a ); } } }
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: 4 value of a: 5 value of a: 6 value of a: 7
Scala for Loop with 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.
import scala.util.control.Breaks._ breakable { for (var x <- Range) { if (condition) { break // terminate the loop } statement(s) } }
Example
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) } } } }
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.