Scala For Loop | For Loop in Scala: Explained
Updated on Jul 03, 2023 | 12 min read | 6.8k views
Share:
For working professionals
For fresh graduates
More
Updated on Jul 03, 2023 | 12 min read | 6.8k views
Share:
Table of Contents
In Scala, a for-loop is also known as for-comprehensions. It can be used to iterate, filter, and return a rehearsed collection. The for-comprehension looks quite similar to a for-loop in imperative languages; however, the difference is that it puts together a list of the results of alliterations.
Check out our free courses to get an edge over the competition
There are several forms of for-loop in Scala, which are as described below:
Syntax
The most uncomplicated syntax of a for-loop with ranges in Scala is as shown below:
for( var x <- Range ){
statement(s);
}
As depicted above, the Range could be any range of numbers, represented as i to j or sometimes like i until j. The left-arrow ← operator is known as a generator because it generates individual values from a range.
Alternatively, one can also also use the syntax:
for(w <- range){
// Code..
}
Here, w is a variable, the left-arrow sign ← operator is the generator, and the range is the value which holds the starting and the ending values. The range is represented by using either i to j or i until j.
Using ‘to’ with for-loop includes both the starting and the ending values. In the example shown below, we can use ‘to’ for printing values between 0 to n. In other words, the loop starts from 0 and ends at 10, which means we can print page numbers 0 to 10.
// Scala program to illustrate how to
// create for loop using to
object Main
{
def main(args: Array[String])
{
println(“The value of w is:”);
// Here, the for loop starts from 0
// and ends at 10
for( w <- 0 to 10)
{
println(w);
}
}
}
Check out upGrad’s Advanced Certification in Cyber Security
Output:
In the example shown above, the value of w is:
0
1
2
3
4
5
6
7
8
9
10
Read: Top 10 skills to become a full stack developer
upGrad’s Exclusive Software Development Webinar for you –
SAAS Business – What is So Different?
The difference between using until and to is; to includes the starting and the ending values given in a range, whereas until excludes the last value of the given range. In the for-loop example illustrated below, we can use until to print values between 0 to n-1. In other words, the loop starts at 0 and ends at n-1, which comes out to 9. So, we can print page numbers 0 to 9.
// Scala program to illustrate how to
// create for loop using until
object Main
{
def main(args: Array[String])
{
println(“The value of w is:”);
// Here, the for loop starts from 0
// and ends at 10
for( w <- 0 until 10)
{
println(w);
}
}
}
Output:
In the example shown above, the value of w is:
0
1
2
3
4
5
6
7
8
9
Also Read: Python vs Scala
We can also use multiple ranges in a single for-loop. These ranges are separated using a semicolon (;). Let us understand this with the help of an illustration. In the example given below, we have used two different ranges in a single loop, i.e., w <- 0 to 3; z <- 8 until 10.
// Scala program to illustrate how to
// create multiple ranges in for loop
object Main
{
def main(args: Array[String])
{
// for loop with multiple ranges
for( w <- 0 to 3; z<- 8 until 10 )
{
println(“Value of w is :” +w);
println(“Value of y is :” +z);
}
}
}
Output:
Value of w is:0
Value of y is:8
Value of w is:0
Value of y is:9
Value of w is:1
Value of y is:8
Value of w is :1
Value of y is:9
Value of w is:2
Value of y is:8
Value of w is:2
Value of y is:9
Value of w is:3
Value of y is:8
Value of w is:3
Value of y is:9
Checkout: Full Stack Developer Salary in India
Now that you have seen Scala for loop example, learn about if/then/else construct. The if/then/else construct in Scala is similar to other programming languages. It allows you to conditionally execute a block of code based on a boolean expression. Here’s an example:
val x = 10
if (x > 5) {
println("x is greater than 5")
} else {
println("x is less than or equal to 5")
}
Unlike some other languages, Scala does not require an explicit “end if” statement to mark the end of an if/then/else construct. The end of the block is inferred by the closing brace (}).
In Scala, if/else constructs always return a result. This means you can assign the result of an if/else expression to a variable or use it as part of another expression. For example:
val result = if (x > 5) “x is greater than 5” else “x is less than or equal to 5”
println(result)
Scala promotes expression-oriented programming, where most constructs and statements are expressions that return a value. This allows for concise and expressive code. The if/else construct in Scala is an example of expression-oriented programming.
In Scala for loop can have multiple generators, separated by semicolons. Each generator introduces a new variable and a range of values to iterate over. Here’s an example of a for loop with multiple generators:
for { i <- 1 to 3 j <- 1 to 2 } { println(s”i: $i, j: $j”) }
Guards in Scala are conditions that can be added to for loops or pattern matching cases. They allow you to further filter the elements or patterns to be processed. Here’s an example of a for loop with a guard:
for {
i <- 1 to 5
if i % 2 == 0
} {
println(i)
}
Scala supports traditional while loops, where a block of code is repeatedly executed as long as a condition is true. Here’s an example:
var i = 0
while (i < 5) {
println(i)
i += 1
}
Match expressions in Scala are similar to switch statements in other languages. They allow you to match a value against a set of patterns and execute the corresponding code block. Here’s an example:
val day = “Monday”
val result = day match {
case “Monday” => “Start of the week”
case “Friday” => “End of the week”
case _ => “Other day”
}
println(result)
In match expressions, you can use the underscore (_) as a wildcard pattern to match any value. This can be used as a default case when none of the other patterns match. Here’s an example:
val x: Any = "Hello"
val result = x match {
case 1 => "One"
case "Hello" => "Hello"
case _ => "Unknown"
}
println(result)
Scala allows you to handle multiple possible matches on one line using vertical bars (|). This can make your code more concise. Here’s an example:
val day = "Saturday"
val result = day match {
case "Monday" | "Tuesday" | "Wednesday" | "Thursday" | "Friday" => "Weekday"
case "Saturday" | "Sunday" => "Weekend"
case _ => "Unknown"
}
println(result)
In match expressions, you can use if guards in case clauses to add additional conditions for pattern matching. Here’s an example:\
val x = 10
val result = x match {
case even if even % 2 == 0 => “Even”
case _ => “Odd”
}
println(result)
Match expressions work seamlessly with case classes in Scala. Case classes provide a convenient way to define immutable data structures. Here’s an example:
case class Person(name: String, age: Int)
val person = Person(“Alice”, 30)
val result = person match {
case Person(“Alice”, age) => s”Alice, age $age”
case Person(name, age) => s”Other person, name $name, age $age”
}
println(result)
Scala allows you to use a match expression as the body of a method. This can be useful when you want to encapsulate pattern matching logic into a reusable method. Here’s an example:
def getMessage(day: String): String = day match {
case “Monday” => “Start of the week”
case “Friday” => “End of the week”
case _ => “Other day”
}
println(getMessage(“Monday”))
Match expressions in Scala support various types of patterns, including constant patterns, variable patterns, tuple patterns, list patterns, and more. This makes them highly versatile and powerful. Here’s an example:
val x: Any = List(1, 2, 3)
val result = x match {
case 1 => “One”
case List(1, 2, 3) => “List with 1, 2, 3”
case (a, b) => s”Tuple with elements $a and $b”
case _ => “Unknown”
}
println(result)
Scala provides a try/catch/finally construct for exception handling. You can use it to catch and handle exceptions that may occur during the execution of your code. Here’s an example:
try {
// Code that may throw an exception
} catch {
case ex: Exception => println(“Exception occurred: ” + ex.getMessage)
} finally {
// Code that will always execute, regardless of whether an exception was thrown or not
}
In Scala, we can use for-loop to efficiently iterate collections like list, sequence, etc., either by using a for-each loop or a for-comprehensions loop. The syntax of a for-loop with collections in Scala is as shown below:
Syntax
for( var x <- List ){
statement(s);
}
Here, the variable list is a collection type with a list of elements and a for-loop iterates through all the elements returning one element in x variable at a time.
Let us look at the demo program given below to understand a for-loop with collections. In the illustration, we have created a collection using the List variable to list authors based on their ranks.
// Scala program to illustrate how to
// use for loop with collection
object Main
{
def main(args: Array[String])
{
var rank = 0;
val ranklist = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
// For loop with collection
for( rank <- ranklist){
println(“Author rank is : ” +rank);
}
}
}
Output:
Author rank is: 1
Author rank is: 2
Author rank is: 3
Author rank is: 4
Author rank is: 5
Author rank is: 6
Author rank is: 7
Author rank is: 8
Author rank is: 9
Author rank is: 10
For-loop in Scala allows you to filter elements from a given collection using one or more if statements in for-loop. Users can also add more than one filter to a ‘for’ expression using semicolons (;) to separate them. Listed below is the syntax for for-loop with filters.
Syntax
for( var x <- List
if condition1; if condition2…
){
statement(s);
}
Let us understand this better with the help of an example. The illustration given below uses two filters to segregate the given collection. For instance, in the sample below, the filters eliminate the list of authors with ranks greater than 2 and less than 7.
// Scala program to illustrate how to
// use for loop with filters
object Main
{
def main(args: Array[String])
{
var rank = 0;
val ranklist = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
// For loop with filters
for( rank <- ranklist
if rank < 7; if rank > 2 )
{
println(“Author rank is : ” +rank);
}
}
}
Output:
Author rank is: 3
Author rank is: 4
Author rank is: 5
Author rank is: 6
In Scala, the loop’s return value is stored in a variable or may return through a function. To do this, you should prefix the body of the ‘for’ expression with the keyword yield. Listed below is the syntax for for-loop with yield.
Syntax
var retVal = for{ var x <- List
if condition1; if condition2…
}
yield x
Note − The curly braces list the variables and conditions, and retVal is a variable where all the values of x will be stored in the form of collection.
Let us understand this better with the help of an illustration. In the example given below, the output is a variable where all the rank values are stored in the form of a collection. The for-loop displays only the list of authors whose rank is greater than 4 and less than 8.
// Scala program to illustrate how to
// use for loop with yields
object Main
{
def main(args: Array[String])
{
var rank = 0;
val ranklist = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
// For loop with yields
var output = for{ rank <- ranklist
if rank > 4; if rank != 8 }
yield rank
// Display result
for (rank <- output)
{
println(“Author rank is : ” + rank);
}
}
}
Output:
Author rank is: 5
Author rank is: 6
Author rank is: 7
Author rank is: 9
Author rank is: 10
Learn Software Development Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.
If you’re interested to learn more about full-stack software development, check out upGrad & IIIT-B’s Executive PG Program in Full-stack Software Development which is designed for working professionals and offers 500+ hours of rigorous training, 9+ projects, and assignments, IIIT-B Alumni status, practical hands-on capstone projects & job assistance with top firms.
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
India’s #1 Tech University
Executive PG Certification in AI-Powered Full Stack Development
77%
seats filled
Top Resources