3
下面是從樓梯書爲例:lazyMap其實不懶惰?
object Example1 {
def lazyMap[T, U](coll: Iterable[T], f: T => U) = {
new Iterable[U] {
def iterator = coll.iterator.map(f)
}
}
val v = lazyMap[Int, Int](Vector(1, 2, 3, 4), x => {
println("Run!")
x * 2
})
}
結果在控制檯:
Run!
Run!
Run!
Run!
v: Iterable[Int] = (2, 4, 6, 8)
這是怎麼偷懶?