Loop
For
object Demo
{
def main(args : Array[String])
{
var i : Int = 0;
for(i <- 1 to 10) // 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
println(i);
}
}
object Demo
{
def main(args : Array[String])
{
var i : Int = 0;
for(i <- 1 until 10) // 1, 2, 3, 4, 5, 6, 7, 8, 9
println(i);
}
}
object Demo
{
def main(args : Array[String])
{
var i : Int = 0;
var j : Int = 0;
for(i <- 1 to 3; j <- 1 to 3) // nest loop
println(i*10+j);
}
}
For and IF
object Demo
{
def main(args : Array[String])
{
var i : Int = 0;
for(i <- 1 to 10; if i%2 == 0) // 2, 4, 6, 8, 10
println(i);
}
}
Yield
object Demo
{
def main(args : Array[String])
{
var i : Int = 0;
var retVal = for{i <- 1 to 10; if i%2 == 0} yield i
for(i <- retVal)
println(i);
}
}
While
object Demo
{
def main(args : Array[String])
{
var i : Int = 0;
while ( i < 10) // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
{
println(i);
i += 1;
}
}
}
Break
import scala.util.control._
object Demo {
def main(args: Array[String]) {
var a = 0;
val loop = new Breaks;
loop.breakable {
for( a <- 1 to 10){
println( "Value of a: " + a );
if( a == 4 ){
loop.break;
}
}
}
println( "After the loop" );
}
}
Reference