qed
qed

Reputation: 23154

lazyMap is actually not lazy?

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: 178

Answers (1)

Garrett Hall
Garrett Hall

Reputation: 30042

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

Related Questions