Skip to content

Instantly share code, notes, and snippets.

@thetrav
Created October 10, 2012 07:18
Show Gist options
  • 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() }
]}
}
}
@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