Skip to content

Instantly share code, notes, and snippets.

@xlson
Created June 15, 2011 13:59
Show Gist options
  • Save xlson/1027159 to your computer and use it in GitHub Desktop.
Save xlson/1027159 to your computer and use it in GitHub Desktop.
Lazy implementation of collect for Groovy
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