Several ways to define closures
Map = [' A ': 1, ' B ': 2]//simple declaration, anonymous closuremap.each{key, value--map[key] = value * 2}assert Map = = [A:2, b:4]//assignment to Variablesdoubler = {key, value, Map[key] = value *2}map.each (doubler) Assert map = = [A:4, b : 8]//use clousure keyword to define a closure objectdef closure doubling () { return {key, value, Map[key] = value *2}}map.each (doubling ()) assert map = = [A:8, b:16]//instance MethodDef doublemethod (entry) { Map[entry.key] = Entry.value*2}doubler2 = This.&doublemethodmap.each (doubler2) Assert map = = [A:16, b:32]
The parameters of a closure do not need to be explicitly defined. Also, the specified type for the parameter display in the closure is checked only at run time, not at compile time.
Closures can use variable-length parameters, and provide default parameter values.
The method of closure in closed packet class
2.1 Call () method
2.2 Getparametertypes () method: Obtain the parameter information of the closure
2.3 Curry () method to return a new closure after specifying a value for the closure parameter
2.4 iscase () method, with the grep method and the case branch in the switch block
Understand scopes in closures (scoping)
The scope of the closure is the sum of all variables that can be accessed within the closure, and the scope of the closure defines:
A) which local variables can be accessed
b) This means that the closure itself
c) Which fields and method can be accessed from within the closure
Closures have declarer (declarators) and caller (callers). Inside the closure, the variable caller points to the caller, the variable this.owner, or the owner points to declarer.
At the same time, the birthday context of the closure is preserved. Any method that is called at the same time within the closure will be proxied (delegated to) on the declarator, which is the object referenced by the owner variable.
Class Mother {int field = 1 int foo () { return 2} Closure birth (param) { def local = 3 def Closure = {caller -- [This, field, Foo (), local, param, caller, owner] } return closure }}mother julia = new mother () CLO sure = Julia.birth (4) context = Closure.call (this)//the ' this ' referenceprintln context[0].class.nameprintln context[ 1..4]//the caller println context[5].class.name//the owner here points to the declarer of the This closure.println conte XT[6] = = Context[0]//output mother[1, 2, 3, 4]consolescript4true
Learning groovy-Closures