Scala Tutorial
Basics
Control Statements
OOP Concepts
Parameterized - Type
Exceptions
Scala Annotation
Methods
String
Scala Packages
Scala Trait
Collections
Scala Options
Miscellaneous Topics
In Scala, just like in many other programming languages, you have loops for executing a block of code multiple times. Among these, while
and do-while
loops are the iterative constructs provided by the language.
The while
loop repeatedly executes a block of code as long as the given condition is true
.
Syntax:
while(condition) { // code to be executed }
Example:
var i = 0 while (i < 5) { println(i) i += 1 }
This will print numbers 0 through 4.
The do-while
loop is similar to the while
loop, but with one key difference: the code block is executed at least once before the condition is tested because the condition is checked after executing the block.
Syntax:
do { // code to be executed } while(condition)
Example:
var j = 0 do { println(j) j += 1 } while (j < 5)
This will also print numbers 0 through 4.
Order of Execution: In the while
loop, the condition is checked before the execution of loop statements. In the do-while
loop, loop statements are executed at least once before the condition is tested because the condition is checked after the loop body.
Use Case: Use a while
loop if you're unsure if the loop body should be executed at all. Use a do-while
loop if you know the loop body should be executed at least once.
It's worth noting that Scala, being a functional programming language, also encourages the use of functional constructs over traditional loops. For example, you could use recursion, higher-order functions, or constructs like for
comprehensions to achieve many of the same tasks in a more functional style.
How to use while loop in Scala:
// Using while loop var i = 0 while (i < 5) { println(s"Current value of i: $i") i += 1 }
Example of a while loop in Scala:
// Example of a while loop var i = 1 while (i <= 5) { println(s"Number: $i") i += 1 }
Conditionals and loops in Scala with examples:
// Using conditionals and loops var i = 0 while (i < 10) { if (i % 2 == 0) { println(s"Even number: $i") } else { println(s"Odd number: $i") } i += 1 }
Scala while loop vs for loop:
// Scala while loop vs for loop // Using while loop var i = 0 while (i < 5) { println(s"While loop: $i") i += 1 } // Using for loop for (j <- 0 until 5) { println(s"For loop: $j") }
Using break and continue in Scala while loop:
break
and continue
statements, but similar behavior can be achieved using boolean flags and if
statements.// Using break and continue in Scala while loop var i = 0 var breakLoop = false while (i < 10 && !breakLoop) { if (i == 5) { breakLoop = true } else { println(s"Current value: $i") } i += 1 }
Nested while loops in Scala:
// Nested while loops var i = 1 while (i <= 3) { var j = 1 while (j <= 3) { println(s"Outer: $i, Inner: $j") j += 1 } i += 1 }