bdumon (1) [Avatar] Offline
#1
I have two questions/remarks on section 8.2.3, more specifically the part starting with "This is fine for loops like for and while; but when looping with closures as in an [1..3].each{} loop, you have to call the NodeBuilder like builder.invoice ..."

1)

Shouldn't "[1..3].each{}" be "(1..3).each{}" ?


2)

Further on it is mentioned that "The closure passed to each will have a delegate of the calling context (the script), ..."

I would think that the closure passed to the each has as calling context the closure in which it is nested, rather than the script. So method calls within the closure passed to each, would then be delegated to the containing closure, which again delegates to its delegate, which is the builder. So it seems to me things should work without the "builder." before invoice.

I verified this by modifying listing 8.5 to use the (1..3).each{} construct, and it works just the same as with the for loop. Though maybe this is related to the fact I'm using Groovy 1.5.

Just an extract for clarification:

def invoices = builder.invoices {
(1..3).each {day ->
//for(day in 1..3) { //#1
invoice(date: new Date(107,0,day)){
item(count:day){
product(name:'ULC', dollar:1499)
}
}
}
}
Mittie (397) [Avatar] Offline
#2
Re: Possible error in section 8.2.3, Smart building with logic
> Shouldn't "[1..3].each{}" be "(1..3).each{}" ?

Yes, it should. Thanks for spotting this. Erratum added http://groovy.canoo.com/errata/erratum/show/33
although strictly speaking even [1..3].each{} is valid code. Do you know what it does? smilie

> 2)
..
> I would think that the closure passed to the each has
> as calling context the closure in which it is nested,
> rather than the script. So method calls within the
> closure passed to each, would then be delegated to
> the containing closure, which again delegates to its
> delegate, which is the builder. So it seems to me
> things should work without the "builder." before
> invoice.

True. The book text was correct at the time of writing but
meanwhile, Groovy has become more intuitive and
consistent in this area.

Thanks a lot for posting
Dierk