Skip to content

Instantly share code, notes, and snippets.

@xlson
Created September 30, 2010 21:05
Show Gist options
  • Save xlson/605326 to your computer and use it in GitHub Desktop.
Save xlson/605326 to your computer and use it in GitHub Desktop.
Implementation of a list.lazyCollect that will defer execution of the collect closure until get(i) is called
// Impl of a lazyCollect method that will not execute
// until you actually ask for the value
class LazyCollectList extends AbstractList {
private Closure collectClosure
private List backingList
private Map cached = [:]
def get(int i) {
if(!cached.containsKey(i)) {
cached[i] = collectClosure(backingList[i])
}
cached[i]
}
int size() {
backingList.size()
}
}
List.metaClass.lazyCollect = { Closure cl ->
new LazyCollectList(collectClosure: cl, backingList: delegate)
}
assert [1, 2, 3].lazyCollect{ it * 2 } == [2, 4, 6]
def collectWasCalled = false
[1, 2, 3].lazyCollect{ collectWasCalled = true }
assert collectWasCalled == false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment