John P
John P

Reputation: 1580

Access to variables outside groovy closure

I'm processing a log file line-by-line in an eachLine closure and need to remember the value from a previous iteration. The problem is the scope of the "currentCampaign" variable inside the loop is apparently different than outside the loop, so it is not remembered between each iteration. (basically, one line will have the campaign id, then I scan forward for the next instance of a like containing "redirectLink". I need to remember what the last campaignId was in the file)



    def currentCampaign = ""
    file.eachLine{ line->
        if(line.indexOf("campaignId") != -1){
            currentCampaign = extractCampaign(line)
        }
        if(line.indexOf("redirectlink") != -1){
            recordRedirect(currentCampaign, extractRedirectLink(line))
        }
    }


Upvotes: 2

Views: 3128

Answers (1)

jlb
jlb

Reputation: 689

Have you tried a simpler example? At least under groovy 1.8.0, currentCampaign's scope should extend throughout your example.

def last = 0
[5, 3, 9].each {
    def result = last + it
    last = it
    result
}
println last // prints 9

Upvotes: 2

Related Questions