Skip to content

Instantly share code, notes, and snippets.

@thetrav
Created October 10, 2012 07:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thetrav/3863691 to your computer and use it in GitHub Desktop.
Save thetrav/3863691 to your computer and use it in GitHub Desktop.
Groovy Lazy Instance Variables
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
}
}
}
}
@Mixin(LazyVariables)
class SomeClient {
SomeClient() {
lazy([
foo: { makeAnExpensiveCall() }
]}
}
}
@thetrav
Copy link
Author

thetrav commented Oct 10, 2012

Is this too crazy/magic?

@azzamallow
Copy link

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment