Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 699
qed Avatar asked Dec 08 '25 22:12

qed


1 Answers

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>
like image 157
Garrett Hall Avatar answered Dec 11 '25 15:12

Garrett Hall