Updated March 28, 2023
Introduction to Scala While Loops
In any of the Programming Language, the looping concept is the most important part to deep dive about, since it is very helpful to access and process the items from the collections. Irrespective of the collections being mutable or immutable. One must practice using the loops as it is useful in performing any transformations with the data that comes with the collections such as List, Array, etc.
We do have many forms of loops and different ways of accessing the elements from the collections in Scala, such as While, do-while, for, foreach, etc.
One such type of important concept in looping is While loop and we will discuss it in detail as follows.
What is Scala While Loops?
Like any other programming language such as C, C++, C#, Java, etc., “while loop” functions the same way by following the below protocols.
- Checks whether the given condition is true or not.
- Flows in when the given condition is true else falls out.
- Iterates the loop till it satisfies the condition.
- Executes each and every step/business logic within the loop.
- Make the condition to be/become false.
Also, improper use of this while loop can cause you an “infinite execution of loop”. The only thing that makes the execution step to come out of this loop is “By making the loop condition false“.
While the loop is one of the most widely used conditional iteration techniques. Let’s discuss it a little deeper from now on.
Syntax:
while ( condition(s) ) { logic 1
logic 2
…
… logic n
}
Flow Chart:
Code:
object Demo {
def main(args: Array[String]) : Unit = {
var n = 0
// while loop execution starts from here
while ( n < 5 )
{
println ( s" Hello World $n times " )
n += 1 // increments the value of n by 1
}
}
}
Output:
In the above program, the loop starts with the condition and executes until it satisfies the same condition until we make the condition to be “false”.
Unit: the type “Unit” is used as a return type of a function that does not return a value. It will become a unit value by default. We can say that it is similar to the “void” return type in Java. we can specify the function to be unit if it is necessary to have a function that returns nothing. Let’s look into the below examples on this topic and try it out in the Scala interpreter.
Examples to Implement Scala While Loops
Below are the examples of Scala While Loops:
Example #1
Code:
object Demo {
def main ( args: Array [ String ] ): Unit = {
println (" Hello World ")
}
Output:
In the above example, the main function does not need to return any value as it is used to initiate the program flow, we have defined the return type as Unit here.
Example #2
“When we try to return an integer value for the function which is defined with return type as Unit”
Code:
object Demo {
def unitTest() : Unit = { val a=10
a
}
def main ( args: Array [ String ] ): Unit = {
// println("Hello, World!")
println( unitTest() )
}
}
Output:
Example #3
Corrected with the appropriate return type.
Code:
object Demo {
def unitTest( ) : Int = { val a = 10
a
}
def main ( args: Array [ String ] ): Unit = {
// println( "Hello, World! " )
println( unitTest( ) )
}
}
Output:
Impact of having While Loop?
Now we might think that both the while & do-while loops return values of unit type and does not return any value that can be stored in the Val or Var. Then, what could be the impact it does to your code anyways?
Both form of while loops do make the difference by updating the vars or other mutable objects (such as Map, Seq, Set, Buffer, Queue, etc..,) whichever is specified along with the execution steps.
Example #4
Realtime Usage: These types of loops come handy when we try to check the conditions on reading and writing of the file streams.
Code:
import scala.io.Source
object Demo {
def unitTest( ) : Unit = {
val bufferedSource = Source.fromFile( "iso_8859-1.txt" )
for ( line <- bufferedSource.getLines ) {
while(line != "") { println ( line )
}
}
}
def main ( args : Array [ String ] ) : Unit = {
// println( "Hello, World! " ) unitTest()
}
}
Output:
Source File.
Output Format: After Reading
The condition has been applied and returns only the non-blank columns as below.
Conclusion
When we are in need to check for the condition before executing the actual statements (Business Logics), we must go for “while loop”. Since, the loop will get executed only when the condition satisfies, as well as it also saves the execution time by not triggering the unnecessary execution steps. And, if we need our business logic to be applied at least once, before checking the actual conditions, we can proceed with the do-while loop. Also, we should be more cautious about not causing both “while loop” and “do-while loop” to be infinite.
Recommended Articles
This is a guide to Scala While Loops. Here we discuss a brief overview of Scala While Loops and its different examples along with code Implementation. You can also go through our other suggested articles to learn more –