为什么会这样,
scala> List(1,2,3,4).iterator.map((x: Int) => println(x))
不打印出来
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?
换句话说,为什么迭代器上的映射将类型 T 映射到 Unit 并且具有副作用而无法显示这些副作用?
Edit:
另外,如果迭代器是惰性的,为什么下面的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)