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?
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With