Showing posts with label each. Show all posts
Showing posts with label each. Show all posts

Wednesday, June 9, 2010

take care when using it in groovy each loop

One mistake I am making over and over is the following situation:

 def someCollection = [...]
 someCollection.each{
   println it // it works here
   doSomethingWithClauses{
     println it // it cannot be resolved here
   }
 }

As soon as you use the it in encapsulated code {}, it cannot be resolved anymore. It took me ages to find that mistake in the first place, but unfortunately I produce something like that quite often and then I wonder what the hell is wrong.

What you have to do to make it right is giving the iteration variable another name:

 def someCollection = [...]
 someCollection.each{ someItem ->
   println someItem // it works here
   doSomethingWithClauses{
     println someItem // hey cool it works here too
   }
 }