groovy-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Guillaume Laforge <glafo...@gmail.com>
Subject Re: A strange script
Date Sat, 21 Jan 2017 16:19:21 GMT
x doesn't capture the value "a".
Your GString contains a "a", and when you call a() you pass the string "a"
to it.
So the a() call return "a", and you print "a", so you see the output as
well as the println of "a", thus two "a"'s.

Not sure how you came with that code. It's pretty confusing.
Normally, if you use a one-arg closure inside a GString, the parameter of
the closure is actually a writer against which you can write. You're not
supposed to print from there or have side effects.

What are you trying to achieve here?

Guillaume

On Sat, Jan 21, 2017 at 4:46 AM, Yang Yang <reliveyy@gmail.com> wrote:

> Sorry, after reading that part of documentation I still feel a bit
> confused.
>
> groovy:000> "a${x->println x}"
> a
> a
> ===> a
> groovy:000> a = {x->println x}
> ===> groovysh_evaluate$_run_closure1@737a135b
> groovy:000> a("a${x->println x}")
> a
> a
> ===> null
>
> Say "a${a}" will be expanded as "a${x->println x}" and I don't understand
> why x captured the value "a" ?
>
> "a${x->println x}" will output "a" because ${x->println x} will be lazy
> evaluated. Then the result "a" is magically captured by the closure {x->println
> x} and it print another "a". But if it like so then the first return ===>
> should be null.
>
>
>
> On 20 Jan 2017, at 16:49, Guillaume Laforge <glaforge@gmail.com> wrote:
>
> Hi Yang,
>
> Interpolated values in a GString that are closures are executed.
> Have a look at the documentation which shows some examples of this:
> http://groovy-lang.org/syntax.html#_special_case_of_interpolating_closure_
> expressions
>
> Guillaume
>
>
> On Fri, Jan 20, 2017 at 8:22 AM, Yang Yang <reliveyy@gmail.com> wrote:
>
>> *Script:*
>> a = {x -> println x}
>> a("a${a}")
>>
>> *Output:*
>> a
>> a
>>
>> Why?
>>
>
>
>
> --
> Guillaume Laforge
> Apache Groovy committer & PMC Vice-President
> Developer Advocate @ Google Cloud Platform
>
> Blog: http://glaforge.appspot.com/
> Social: @glaforge <http://twitter.com/glaforge> / Google+
> <https://plus.google.com/u/0/114130972232398734985/posts>
>
>
>


-- 
Guillaume Laforge
Apache Groovy committer & PMC Vice-President
Developer Advocate @ Google Cloud Platform

Blog: http://glaforge.appspot.com/
Social: @glaforge <http://twitter.com/glaforge> / Google+
<https://plus.google.com/u/0/114130972232398734985/posts>

Mime
View raw message