2015-10-17 155 views
3

下面是从楼梯书为例:lazyMap其实不懒惰?

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) 

这是怎么偷懒?

回答

4

它之所以被调用地图功能,是因为你在呼吁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>