简体   繁体   中英

Groovy: How to remember closure's variable value between executions?

I would like to be able to do something like this:

def closure = { 
  def a // create new variable, but ONLY if not created yet
  if (a == null) {
    a = 0
  }
  a++
  print a
}

closure() // prints 1
closure() // prints 2
closure() // prints 3, etc...

I want to create the variable INSIDE the closure, not in outer scope.

This may be an invalid answer but the outer scope doesn't need to be global; it can be inside a function for example, or even an anonymous function like:

def closure = {
    def a
    return { 
        if (a == null) a = 1
        println a++ 
    }
}()

closure() // prints 1
closure() // prints 2
closure() // prints 3, etc...

The purpose of the surrounding anonymous function is just to give scope to the a variable without polluting the global scope. Notice that that function is being evaluated immediately after its definition.

This way, the scope of a is effectively "private" to that closure (as it is the only one with a reference to it once the outer function has been evaluated). But the variable is being defined before the first closure() call, so this might not be what you are looking for.

You can do something like this:

def closure = { 
  if( !delegate.hasProperty( 'a' ) ) {
    println "Adding a to delegate"
    delegate.metaClass.a = 0
  }
  delegate.a++
  println delegate.a
}

closure() // prints 1
closure() // prints 2
closure() // prints 3, etc...

But that's a nasty side-effect, and if you don't take care it's going to bite you hard (and any sort of multi-threading will fail horribly)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM