当前位置:网站首页>Closure of groovy

Closure of groovy

2022-06-22 14:37:00 Leisurely summer

1、 Introduce

Closure (Closure) Is a very important concept in many programming languages , that Groovy What is a closure in , The official definition is “Groovy Closure in is an open , Anonymous code block , Parameters... Are acceptable , Returns a value and assigns it to a variable ”, In short , He said an anonymous code block , Parameters... Are acceptable , There is a return value ,

2、 Closure Syntax

{ Parameter type Variable name -> Execute statement }        If there is no parameter , I could just write it as { Execute statement }

Closure can be invoked in two ways : Mode one : Closure name .call()          Mode two : Closure name ()

def test = { println 'hello world' }
//  There are two ways to call 
test.call() //  Mode one 
test() //  Mode two 

3、 Pass parameters in closures

def test = { String name -> println "hello world ${name}" } //  When multiple parameters need to be passed in , Use commas to separate 
test.call(" Zhang San ") //  Mode one 
test("zhangsan") //  Mode two 

//  There is a default parameter in the closure   be called  it
def test1 = { println "hello world ${it}" }
test1.call(" Default ")

//  The return value of the closure 
def test2 = { String name -> println "hello world ${name}" }   //  Closures are not defined return Statement but still has a return value , The return value is null
def result = test2.call(" Return value ")
println(result)

 

4、 Closures are used in conjunction with basic types

4.1、 Use upto Method to find factorial

int x = fab(5)
println x

int fab(int number) { //  Factorial of 
    int result = 1
    1.upto(number, { num -> result *= num })
    return result
}

4.2、 Use down Method to find factorial

int x = fab2(5)
println x
int fab2(int number) {
    int result = 1
    number.downto(1) {
        num -> result *= num
    }
    return result
}

4.3、 Use times Method cumulative summation

int x = fab3(5)
println x
//  Cumulative sum 
int fab3(int number) {
    int result = 0
    number.times { num -> result += num }
    return result
}

5、 The combination of strings and closures

5.1、each Method to traverse the string

String str = '1study groovy2'
// each Method to traverse the string 
str.each {
        // each The return value of the method is still the caller itself 
    String temp -> println temp
}

5.2、find Method to find the first

str.find {
    String s -> s.isNumber()  // find The closure of a method must be a return value of boolean type 
}

5.3、findAll Method to find all eligible elements

str.findAll {
    String s -> s.isNumber() //  The return value is a collection 
}

5.4、any Method

any The value of the method is Boolean , As long as any element in the string meets the conditions in the closure, it is true, Instead of false

str.any {
    String s -> s.isNumber()
}

5.5、every Method

every The value of the method is Boolean , Each element in the string must meet the conditions in the closure to be true, Instead of false

str.every {
    String s -> s.isNumber()
}

5.6、collect Method

collect The return value of the method is list aggregate

def list2 = str.collect {
    it.toUpperCase()
}
println list2.toListString()

6、 Three important variables in closures :this, owner, delegate

this Keyword represents the class at the closure definition ,owner Keyword represents the class or object at the closure definition ,delegate Keyword represents any object , Default and owner Agreement

//  Define a closure in a closure 
def nestClosure = {
    def innerClosure = {
        println "innerClosure this:" + this //  Points to the nearest class , Script class 
        println "innerClosure owner:" + owner //  Point to the nearest object 
        println "innerClosure delegate:" + delegate //  Default and owner bring into correspondence with 
    }
    Person p = new Person()
    innerClosure.delegate = p //  Modify the default delegate,  After modification delegate And owner The object pointed to is different 

    innerClosure.call()
}
nestClosure.call()

 

7、 The delegation strategy of closures

/*  The delegation strategy of closures  */
class Student {
    String name
    def pretty = {"My Name is ${name}"}

    String toString() {
        pretty.call()
    }
}

class Teacher {
    String name
}
Student stu = new Student(name: 'salary')
Teacher tea = new Teacher(name: ' teacher ')
//  By modifying the delegate The implementation will Teacher Medium name Property substitution Student Properties in 
stu.pretty.delegate = tea
//  Modify strategy , Default Closure.OWNER_FIRST
stu.pretty.resolveStrategy = Closure.DELEGATE_FIRST //  If delegate There is no name This attribute , Then he will be owner In search of ,Closure.DELEGATE_ONLY, If delegate There is no name When this property , You're going to report a mistake 
println stu.toString()

原网站

版权声明
本文为[Leisurely summer]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206221317373814.html