这是楼梯书中的一个例子:
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)
这是多么懒惰?
答案 0 :(得分:4)
它调用map函数的原因是因为您在Scala控制台中运行,该控制台调用lazyMap上的toString
函数。如果您确保不在代码末尾添加""
来返回值,则不会映射:
scala> def lazyMap[T, U](coll: Iterable[T], f: T => U) = {
new Iterable[U] {
def iterator = coll.iterator.map(f)
}
}
lazyMap: [T, U](coll: Iterable[T], f: T => U)Iterable[U]
scala> lazyMap[Int, Int](Vector(1, 2, 3, 4), x => {
println("Run!")
x * 2
}); ""
res8: String = ""
scala>