Thank you Graeme,
It's exactly what I wanted to achieve.
Applied to my example, we can write:
test.with {
println prop1
println prop2
}
Best regards,
Bertrand.
-----Message d'origine-----
De : graeme.rocher@(protected)
Envoyé : vendredi 29 août 2008 13:14
À : user@(protected)
Objet : Re: [grails-user] Implementing the Delphi "with" instruction in Groovy
There is already a with method in Groovy
http://groovy.codehaus.org/groovy-jdk/java/lang/Object.html#with(
groovy.lang.Closure%20closure)
Cheers
On Fri, Aug 29, 2008 at 8:49 AM, Goetzmann Bertrand
<BGoetzmann@(protected):
> 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
>
>
>
--
Graeme Rocher
Grails Project Lead
G2One, Inc. Chief Technology Officer
http://www.g2one.com
---------------------------------------------------------------------
To unsubscribe from this list, please visit:
http://xircles.codehaus.org/manage_email
---------------------------------------------------------------------
To unsubscribe from this list, please visit:
http://xircles.codehaus.org/manage_email