Skip to content

Instantly share code, notes, and snippets.

@purplefox
Created March 27, 2012 09:45
Show Gist options
  • Save purplefox/2214446 to your computer and use it in GitHub Desktop.
Save purplefox/2214446 to your computer and use it in GitHub Desktop.
In JavaScript I can do this: (setTimer is just a vertx function which calls the specified handler function at some time (100 ms) in the future.)
var id = vertx.setTimer(100, function() {
stdout.println("id is " + id);
});
This works because the function is a closure, and id is declared (but not initialised) before setTimer is executed.
But if I try to do the same in Groovy it complains that id is not recognised
def id = Vertx.instance.setTimer(100, {
println "is is " + id
})
[junit] groovy.lang.MissingPropertyException: No such property: id for class: core.timer.testClient
I can get it to work in Groovy by declaring id on a separate line, but this is pretty ugly:
def id
id = Vertx.instance.setTimer(100, {
println "is is " + id
})
Just wondering... is this by design? I would expect any local variables declared in the scope before a closure to be accessible in the closure. I understand that id won't be *initialised* before setTimer returns, but does that matter?
@purplefox
Copy link
Author

Good answer :)

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