Groovy:如何记住执行之间的闭包的变量值? [英] Groovy: How to remember closure's variable value between executions?

查看:327
本文介绍了Groovy:如何记住执行之间的闭包的变量值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想能够做这样的事情:

  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 ...



我想在闭包中创建变量INSIDE,而不是在外部范围。

解决方案

这可能是一个无效的答案,但外部范围不需要是全局的;它可以在一个函数内,例如,甚至一个匿名函数,如:

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

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

周围匿名函数的目的只是给 a 变量赋值而不污染全局范围。注意,该函数在定义后立即被求值。



这样, a 私有到闭包(因为一旦外部函数被计算,它是唯一一个引用它的)。但是变量在第一个 closure()调用之前被定义,因此这可能不是您要查找的。

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.

这篇关于Groovy:如何记住执行之间的闭包的变量值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆