Running A Groovy Closure In a Groovy Closure

One thing I did not see in the Groovy documentation is how to call a closure on a closure.

While working on my mail server, I wanted to try out some regular expressions on some strings. So I put them in a list, and I ran the list through a closure.

someList.each {
    println "looking at ${it}"
    q = it =~ regex
    print it ==~ regex
    print "; " + ( it?: q[0][2] )
    println "; done with ${it}"
}

Then I wanted to do that with several lists. I did not want to type or copy and paste the closure over and over again.  So I assigned the closure to a name:

regexClosure = {
    println "looking at ${it}"
    q = it =~ regex
    print it ==~ regex
    print "; " + ( it?: q[0][2] )
    println "; done with ${it}"
}

Then I had some problems getting it to work as expected.

Calling someList.each{ regexClosure } did not work.

I tried several guesses and variations until I found a way to call a closure in a closure.

What finally worked was:

someList.each{regexClosure(it)}

You’re welcome.

There are 167 words in this article.