为什么会这样,
当...的时候
scala> List(1,2,3,4).iterator.map((x: Int) => println(x))
不打印输出
1
2
3
4
当...的时候
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))
这是什么意思?
换句话说,为什么一个将类型T映射到Unit并带有副作用的迭代器映射的地图无法显示这些副作用?
编辑:
如果迭代器是惰性的,为什么以下调用lazyMap实际上会从头到尾计算新的迭代器(请提供完整的新迭代器)?
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)