Why is it that,
scala> List(1,2,3,4).iterator.map((x: Int) => println(x))
does not print out
1
2
3
4
while
List(1,2,3,4).map((x: Int) => println(x))
List(1,2,3,4).foreach((x: Int) => println(x))
List(1,2,3,4).iterator.foreach((x: Int) => println(x))
all do?
In other words, why is it that a map on a iterator that maps type T to Unit and has side effects unable to show those side effects?
Edit:
Also why does the following invocation of lazyMap actually computes the new iterator (provide the complete new iterator) from beginning to end if iterator is lazy?
def lazyMap[T, U](coll: Iterable[T], f: T => U) = new Iterable[U] {
def iterator = coll.iterator map f
}
scala> lazyMap(List(1,2,3,4), (x: Int) => x + 1)
res4: java.lang.Object with Iterable[Int] = (2, 3, 4, 5)
Cause map on iterator is lazy and you need some strictness:
When you doing foreach on iterator it is quite obvious that you’re doing side effects, so lazyness will be undesired. I wouldn’t said so about map.
UPD
As for your edit: the reason for such behaviour, is that there is implicit call of toString for statement result which in turn stricts the iterator — try this code on your own:
and you’ll see that function
fis never called