Scala Language Collections Foreach


foreach is unusual among the collections iterators in that it does not return a result. Instead it applies a function to each element that has only side effects. For example:

scala> val x = List(1,2,3)
x: List[Int] = List(1, 2, 3)

scala> x.foreach { println }

The function supplied to foreach can have any return type, but the result will be discarded. Typically foreach is used when side effects are desirable. If you want to transform data consider using map, filter, a for comprehension, or another option.

Example of discarding results

def myFunc(a: Int) : Int = a * 2
List(1,2,3).foreach(myFunc) // Returns nothing