A question about evaluate()

View: New views
2 Messages — Rating Filter:   Alert me  

A question about evaluate()

by Russ Abbott :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

Hi,

I have a couple of additional Groovy questions. I'm sending them in two messages. This one is about evaluate(). Why do I get these results?

def y = "g * 2"
println ([1, 2, 3, 4].collect( {x -> g = x; evaluate(y)} ) ) // => [2, 4, 6, 8]
println ([1, 2, 3, 4].collect( {x -> evaluate(y)} ) )          // => [8, 8, 8, 8]

def z = "h * 2"
println ([1, 2, 3, 4].collect( {h -> evaluate(z)} ) ) // => Exception thrown: groovy.lang.MissingPropertyException: No such property: h for class: Script1

-- Russ.

Re: A question about evaluate()

by Michael Baehr-2 :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

Ok, let me try ...

In

   def y = "g * 2"
   println ([1, 2, 3, 4].collect( {x -> g = x; evaluate(y)} ) ) // =>  
[2, 4, 6, 8]

you assign a value to the variable g, which has not been defined in  
the script. Therefore, it is created in the script's binding.
evaluate uses the same binding for evaluating the given expression,  
hence g is known when calculating "g*2"

In

   println ([1, 2, 3, 4].collect( {x -> evaluate(y)} ) )          //  
=> [8, 8, 8, 8]

g is still in the script's binding and therefore again available  
during evaluate. The last value of g is 4 (from above).

Now, in

   def z = "h * 2"
   println ([1, 2, 3, 4].collect( {h -> evaluate(z)} ) )

h is a parameter for the closure, it is NOT created in the script's  
binding. Therefore, it is not available during evaluation of "h*2", so  
you get a MissingPropertyException.

A "println binding.variables" will show you what's in the binding at  
any time.

cya

Michael

Am 06.07.2008 um 22:18 schrieb Russ Abbott:

> Hi,
>
> I have a couple of additional Groovy questions. I'm sending them in  
> two messages. This one is about evaluate(). Why do I get these  
> results?
>
> def y = "g * 2"
> println ([1, 2, 3, 4].collect( {x -> g = x; evaluate(y)} ) ) // =>  
> [2, 4, 6, 8]
> println ([1, 2, 3, 4].collect( {x -> evaluate(y)} ) )          // =>  
> [8, 8, 8, 8]
>
> def z = "h * 2"
> println ([1, 2, 3, 4].collect( {h -> evaluate(z)} ) ) // =>  
> Exception thrown: groovy.lang.MissingPropertyException: No such  
> property: h for class: Script1
>
> -- Russ.


---------------------------------------------------------------------
To unsubscribe from this list, please visit:

    http://xircles.codehaus.org/manage_email