1. 程式人生 > >Groovy裏面閉包中變量符號的查找與變量定義的限制

Groovy裏面閉包中變量符號的查找與變量定義的限制

ins 結果 查找 ring -- UNC 定義 roo 假設

 1 class a {
 2     def v1 = "v1 in a"
 3     static def v2 = "v2 in a"
 4     def v4 = "v4 in a"
 5     def v5 = "v5 in a"
 6     def va = "va in a"
 7     def b() {
 8         def v1 = "v1 in a.b()"
 9         def v2 = "v2 in a.b()"
10         def v4 = "v4 in a.b()"
11         def g = {
12 def v0 = "v0 in closure g" 13 def h = { 14 //function b裏面已經定義v4 = "v4 in a.b()"所以下面這行 15 //報錯:The current scope already contains a variable of the name v4 16 //def v4 = "v4 in closure h" 17 } 18 } 19 def c = {
20 //下面的這行代碼報錯:The current scope already contains a variable of the name v1 21 //def v1 = "v1 in closure c" 22 println v1 23 println owner 24 println this 25 //下面這行定義v5變量正常,輸出的結果也是:v5 in closure c 26 def v5 = "v5 in closure c" 27
println v5//v4 28 println va 29 } 30 println "***" + c.toString() + "***" 31 c() 32 33 return "b func" 34 } 35 36 def d = { 37 println v1; 38 println v2; 39 println v4; 40 def v5 = "v5 in closure d" 41 println v5 42 } 43 44 def e = { 45 def v1 = "v1 in closure e" 46 def f = { 47 //下面這行代碼報錯:The current scope already contains a variable of the name v1 48 //def v1 = "v1 in closure f" 49 println v1 50 51 //下面這行就沒錯,因為閉包e的v2是在後面定義的 52 def v2 = "v2 in closure f" 53 54 //下面這行報錯,v3在f裏面不可見 55 //println v3 56 57 def vf = "vf in closure f" 58 } 59 f() 60 def v2 = "v2 in closure e" 61 def v3 = "v3 in closure e" 62 63 //在閉包e裏面vf不可見 64 //println vf 65 } 66 } 67 def test(x) { 68 println "func test start --- x:" + x 69 def v1 = 1000 70 def v2 = 2000 71 def v3 = 3000 72 73 x() 74 println "func test--- end:" 75 } 76 test(new a().d) 77 println "--------------" 78 //println new a().v4 79 println new a().b() 80 new a().e() 81 82 83 /* 84 通過上面的測試代碼可以看出: 85 1.在閉包a裏面定義的閉包b,那麽b中定義的變量不能和和閉包a裏面定義的變量名字相同. 86 2.在函數a裏面定義的閉包b,那麽b中定義的變量不能和和函數a裏面定義的變量名字相同. 87 3.由此也可以推導出:在函數a裏面定義閉包b,在閉包b裏面定義閉包c,那麽c中定義 88 的變量也不能和函數a中定義的變量名字相同,對於任意多層閉包嵌套也是如此 89 在閉包裏面的符號查找方面: 90 首先在閉包裏面查找,如果閉包裏面沒有定義,則有兩種情況(假設delegate策略是Closure.OWNER_FIRST,其它策略是一樣的): 91 1.如果這個閉包的外層是函數,則現在函數裏面查找,如果函數裏面也沒有定義,則進入delegate策略即在owner裏面查找, 92 如果owner裏面沒有,則在delegate裏面查找,ruguo delegate裏面沒有就報錯 93 2.如果這個閉包沒外層不是函數,則直接進入delegate策略即在owner裏面查找,如果owner裏面沒有,則在delegate裏面查找 94 如果delegate裏面沒有就報錯. 95 96 */

Groovy裏面閉包中變量符號的查找與變量定義的限制