Author Login
Post Reply
Hello,
In the Delphi language, "with" is a key word that permits to apply a
shortcut with object references.
Here a simple use case with a reference "test" of the hypothetical class
Test:
test.call1();
test.prop1 := 'Hello';
test.call2();
These statements can be replaced by:
with test do
begin
call1();
prop1 := 'Hello';
call2();
end;
The Delphi's compiler is able to resolve the right calls.
"with" permits to have statements clearer and more concise.
So, I ask me how we can do something like this in the Groovy language.
Thinking of this morning, here my first approach using MOP (the code
bellow works in the Groovy console):
// Define a static method "with" on class Object
Object.metaClass.static.with = { Object ref, Closure cl ->
cl.delegate = ref
cl()
}
class Test {
def prop1 = "Salut !"
int prop2
}
def test = new Test()
// "with" in action with the reference "test"
Object.with(test) {
println prop1
println prop2
}
// You can also apply "with" without a reference variable
Object.with(new Test(prop1: 'Hello', prop2: 2)) {
prop2.times {
println prop1
}
}
What do you think about this? Is it a best approach?
Best regards
Bertrand Goetzmann
http://www.odelia-technologies.com
http://www.grailsworks.com
---------------------------------------------------------------------
To unsubscribe from this list, please visit:
http://xircles.codehaus.org/manage_email