| Free tutorials for Java, Eclipse and Web programming |
Scala provides the for loop which iterates over a collection. The function foreach on a collection allows to use a closure (function) on each element.
Objects have also helper functions, for example Integer provides to to() method which allows to count from a starting number object to the defined number.
Create a scala project "de.vogella.scala.loops" and try the following code.
package de.vogella.scala.loops
object Loops {
def main(args: Array[String]) {
val list = List("Java", "Scala" , "Groovy" , "NET");
// Use foreach and print out every element
list.foreach(n=> println(n))
// Use standard for
for (n<-list){
println(n)
}
// Use method to
println
for (i<- 1.to(9)){
print (i)
}
// Use the shorter form
println
for (i<- 1 to 9){
print (i)
}
}
}