2015-10-17 43 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>