Groovy closures

definition

A Closure is a data type that represents a piece of executable code. It can be used as a parameter to a method, or as a return value, or it can run independently. It is defined as follows:

  def xxx = {parameters -> code}  
  def xxx = {no parameters, pure code}

For example, we define a closure named add as follows:

def add = { a, b -> a + b }
println("3+5=" + add(3, 5))

If the closure does not define parameters, it implies a parameter it, similar to this in Java, assuming that your closure does not need to accept parameters, but an implicit parameter it will still be generated, but its value is null, That is, the closure contains at least one parameter.

def greeting = { "Hello Closure, $it!" }
println(greeting('Jack'));
def getStr = { return "abcd:$it" }
println(getStr())

 The output is as follows:

Hello Closure, Jack!
abcd:null

When the closure is used as the last parameter of a closure or method, the closure can be extracted from the parameter parentheses and connected at the end. If the closure is the only parameter, the parentheses where the closure or method parameter is located can also be omitted. .

def run = { int a, Closure c -> c(a) }
println(run( 5) { y -> y * 3 })
def run2 = { Closure c -> c.call() }
run2 {
    println("jack:Closure")
}

 The output is as follows:

15
jack:Closure

If there is no list in the parameter declaration of the closure, the incoming parameters can be set to list, and the parameters inside will be passed into the closure parameters respectively.

def list = [1, 2, 3]
def sum= {a, b, c-> a + b + c}
println(sum(list))

The output is as follows:

6

Closures are nestable

def gcd
gcd={ m,n-> m%n==0? n: gcd(n,m%n) }
println(gcd(28,35))

The output is as follows:

7

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325455193&siteId=291194637