Scala while
Jakob Jenkov |
The Scala while
loop executes a certain block of code, as long as a certain condition is true.
Here is an example:
var myInt : Int = 0; while(myInt < 10) { println("myInt = " + myInt); myInt += 1; }
This while loop would execute 10 times. For each iteration in the loop it would print the value of myInt
,
and then add 1 to myInt
.
do while
Scala also has a do while
loop. The do while
loop is similar to the while
loop except the condition is executed after the loop body. This means that the loop body is always executed
at least once. Here is an example:
var myInt : Int = 0; do { println("myInt = " + myInt); myInt+=1; } while(myInt < 10)
There are situations in a program where it makes sense to always execute the loop body at least once. Thus, the do while loop comes in handy
Omitting the { } in while Loops
Like in if-statements, you can omit the { } in the while loop if the loop body consists of only a single line. Here is an example:
while(someObject.hasNext()) process(someObject.next());
Tweet | |
Jakob Jenkov |