class a {
def v1 = "v1 in a"
static def v2 = "v2 in a"
def v4 = "v4 in a"
def v5 = "v5 in a"
def va = "va in a"
def b() {
def v1 = "v1 in a.b()"
def v2 = "v2 in a.b()"
def v4 = "v4 in a.b()"
def g = {
def v0 = "v0 in closure g"
def h = {
//function b里面已经定义v4 = "v4 in a.b()"所以下面这行
//报错:The current scope already contains a variable of the name v4
//def v4 = "v4 in closure h"
}
}
def c = {
//下面的这行代码报错:The current scope already contains a variable of the name v1
//def v1 = "v1 in closure c"
println v1
println owner
println this
//下面这行定义v5变量正常,输出的结果也是:v5 in closure c
def v5 = "v5 in closure c"
println v5//v4
println va
}
println "***" + c.toString() + "***"
c() return "b func"
} def d = {
println v1;
println v2;
println v4;
def v5 = "v5 in closure d"
println v5
} def e = {
def v1 = "v1 in closure e"
def f = {
//下面这行代码报错:The current scope already contains a variable of the name v1
//def v1 = "v1 in closure f"
println v1 //下面这行就没错,因为闭包e的v2是在后面定义的
def v2 = "v2 in closure f" //下面这行报错,v3在f里面不可见
//println v3 def vf = "vf in closure f"
}
f()
def v2 = "v2 in closure e"
def v3 = "v3 in closure e" //在闭包e里面vf不可见
//println vf
}
}
def test(x) {
println "func test start --- x:" + x
def v1 = 1000
def v2 = 2000
def v3 = 3000 x()
println "func test--- end:"
}
test(new a().d)
println "--------------"
//println new a().v4
println new a().b()
new a().e() /*
通过上面的测试代码可以看出:
1.在闭包a里面定义的闭包b,那么b中定义的变量不能和和闭包a里面定义的变量名字相同.
2.在函数a里面定义的闭包b,那么b中定义的变量不能和和函数a里面定义的变量名字相同.
3.由此也可以推导出:在函数a里面定义闭包b,在闭包b里面定义闭包c,那么c中定义
的变量也不能和函数a中定义的变量名字相同,对于任意多层闭包嵌套也是如此
在闭包里面的符号查找方面:
首先在闭包里面查找,如果闭包里面没有定义,则有两种情况(假设delegate策略是Closure.OWNER_FIRST,其它策略是一样的):
1.如果这个闭包的外层是函数,则现在函数里面查找,如果函数里面也没有定义,则进入delegate策略即在owner里面查找,
如果owner里面没有,则在delegate里面查找,ruguo delegate里面没有就报错
2.如果这个闭包没外层不是函数,则直接进入delegate策略即在owner里面查找,如果owner里面没有,则在delegate里面查找
如果delegate里面没有就报错. */