Created
October 10, 2012 07:18
-
-
Save thetrav/3863691 to your computer and use it in GitHub Desktop.
Groovy Lazy Instance Variables
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
class LazyVariables { | |
def lazy(variables) { | |
variables.each { name, init -> | |
def chars = name.toCharArray() | |
chars[0] = Character.toUpperCase(chars[0]) | |
def getter = "get${new String(chars)}" | |
this.metaClass[getter] = { | |
def value = init() | |
this.metaClass[name] = value | |
this.metaClass[getter] = { value } | |
value | |
} | |
} | |
} | |
} |
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
@Mixin(LazyVariables) | |
class SomeClient { | |
SomeClient() { | |
lazy([ | |
foo: { makeAnExpensiveCall() } | |
]} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
does it cache if lazy foo is called a second time?
not crazy, I havnt read much scala so i had to go line by line, but got there :)
im just wondering what the equivalent code in javascript looks like!