For Loop with Counter
The simplest loop syntax is:for (a <- 1 to 5){
println(“Print a: ” + a);
}
Print a: 1
Print a: 2
Print a: 3
Print a: 4
Print a: 5
By default, counter increment is 1. You can change the number of counter increment using "by".
for (a <- 1 to 5 by 2) {
println(“Print a: ” + a);
}
When the above code is compiled and executed, it produces following result:
Print a: 1
Print a: 3
Print a: 5
For Loop with Filter
You can filter out some of the elements. Following is the example of for loop along with filters:for (
a <- 1 to 5
if ( a > 3)
) {
println(“Print a: ” + a);
}
When the above code is compiled and executed, it produces following result:
Print a: 4
Print a: 5
For Loop with Yield
This is one of the awesome feature in Scala where you generate a static type variable using loop. I don’t really see in other programming language.When For loop finishes running, it returns a collection of all these yielded values.
The type of the collection that is returned is the same type that you were iterating over.
// Loop through and generate a variable val i = for ( a <- 1 to 5 if ( a > 3) ) yield { a } // Print the result for( a <- i){ println( "Value of a: " + a ); }When the above code is compiled and executed, it produces following result:
Print a: 4
Print a: 5
No comments:
Post a Comment