Groovy web console

subscribe to the feed Subscribe
to this
for-loop-with-closure (via #groovywebconsole)
tweet this snippet Tweet


Published 9 months ago by Anonymous
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
def templates = []
templates << 'TOMCAT'
templates << 'MEAN'

def steps = [:]

for (String template: templates) {
  // When the closure below is called, it references the `template` var
  // from outside the loop, which has the last value of 'MEAN'. Solution
  // is to create a new var within the loop with the same value.
  steps[template] = { "Run template ${template}" }

for (String t: templates) {
  println("${t}: ${steps[t]()}")

// Output:
// TOMCAT: Run template MEAN
// MEAN: Run template MEAN