Reputation: 23094
Here is an example from the stairway book:
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
})
}
Result in console:
Run!
Run!
Run!
Run!
v: Iterable[Int] = (2, 4, 6, 8)
How is this lazy?
Upvotes: 3
Views: 177
Reputation: 30022
The reason it is calling the map function is because you are running in the Scala console which calls the toString
function on the lazyMap. If you make sure not to return the value by adding a ""
to the end of your code it will not map:
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>
Upvotes: 4