Created
September 30, 2010 21:05
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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