Groovy实践

2019-08-25  本文已影响0人  北雁南飞_8854

闭包(Closure)

一、语法

1.1. 闭包的定义
{ [closureParameters -> ] statements }
说明:
(1)closureParameters是可选的、逗号隔开的参数列表,参数可以是typed、也可以是untyped;
(2)->用来将参数和closure body部分分隔开;
(3)statements有0、1或多条groovy statements组成。

1.2. 举例:

{ item++ }      //在闭包中引用item变量名
{ -> item++ }     //不接受任何参数的闭包、并且仅仅限制于空参的调用。                                 
{ println it }    //打印隐式参数名it
{ it -> println it }                                
{ name -> println name }     //显式定义参数名name
{ String x, int y ->                                
    println "hey ${x} the value is ${y}"
} //接受两个typed参数名x和y

{ reader ->                                         
    def line = reader.readLine()
    line.trim()
} //包含多条语句

可变参数

def concat1 = { String... args ->                                                                                                 
    args.join('')
}
println concat1('abc', 'def') //输出abcdef

def concat2 = { String[] args ->
    args.join('')
}
println concat2('abc', 'def') //输出abcdef

def multiconcat = { int n, String... args-> 
    args.join('') * n 
}
println multiconcat(2, 'abc', 'def') //输出abcdefabcdef

二、Delegation策略

3.2. Owner, delegate and this
this:定义闭包的外围类(enclosing class)
owner: 定义闭包的外围对象(enclosing object),可能是类、也可能是闭包;
delegate:对应一个第三方的对象,默认和owner一样。
举例:test_deleagte.groovy

def myScript = { 
    println "myScript this=" + this     //test_deleagte@22e357dc
    println "myScript owner=" + owner    //test_deleagte@22e357dc                                                                                          
    println "myScript delegate=" + delegate  //test_deleagte@22e357dc

    def innerCloser = { 
        println "innerClouser this =" + this    //test_deleagte@22e357dc
        println "innerClouser owner=" + owner    //test_deleagte$_run_closure1@223aa2f7
        println "innerClouser delegate=" + delegate    //test_deleagte$_run_closure1@223aa2f7
    }   

    innerCloser.call()
}

myScript.call()

使用了delegate之后:

class Person{                                                                                                                  

}

Person p = new Person()

def myScript = { 
    println "myScript this=" + this  //test_deleagte@2df9b86
    println "myScript owner=" + owner //test_deleagte@2df9b86
    println "myScript delegate=" + delegate  //test_deleagte@2df9b86

    def innerCloser = { 
        println "innerClouser this =" + this  //test_deleagte@2df9b86
        println "innerClouser owner=" + owner  //test_deleagte$_run_closure1@3fb1549b
        println "innerClouser delegate=" + delegate  //Person@ea6147e
    }   

    innerCloser.delegate = p 
    innerCloser.call()
}


myScript.call()

使用Deleagte的例子:

class Person {                                                                                                                    
    String name
}
class Thing {
    String name
}

def p = new Person(name: 'Norman')
def t = new Thing(name: 'Teapot')

def upperCasedName = { 
    delegate.name.toUpperCase()
}

upperCasedName.delegate = p 
println upperCasedName()  //NORMAN

upperCasedName.delegate = t 
println upperCasedName() //TEAPOT

更改delegate的例子

class Student{                                                                                                                    
    String name
    def showMe = { 
        return "my name is $name"
    }   

    @Override
    String toString() {
        return showMe();
    }   
}

class Teacher {
    String name
}

def stu = new Student(name : 'tom')
def tea = new Teacher(name : 'Mrs Li')
println stu.toString() //my name is tom

stu.showMe.delegate = tea 
stu.showMe.resolveStrategy = Closure.DELEGATE_FIRST 
println stu.toString() //my name is Mrs Li

```groovy
class Person {                                                                                                                    
    String name
    int age 
    def fetchAge = { age }
}
class Thing {
    String name
}

def p = new Person(name:'Jessica', age:42)
def t = new Thing(name:'Printer')
def cl = p.fetchAge

cl.delegate = p 
println cl() //42

cl.delegate = t 
println cl() //42

cl.resolveStrategy = Closure.DELEGATE_ONLY
cl.delegate = p 
println cl() //42

cl.delegate = t 
println cl() //groovy.lang.MissingPropertyException

gradle 的Task的使用

task hello {
    doLast {
        println 'Hello Earth'
    }   
}
hello.doFirst {
    println 'Hello Venus'
}
hello.configure {
    doFirst {
        println 'Hello First'
    }   
}

hello.configure {
    doLast {
        println 'Hello Jupiter'
    }   
}

输出结果:
Hello First
Hello Venus
Hello Earth
Hello Jupiter

Delegate再举例

class GreetingPluginExtension {                                                                                                 
    String message
    String greeter
}

def greeting = { 
    message = 'Hi'
    greeter = 'Gradle'
}

def g = new GreetingPluginExtension(message:'', greeter:'')
greeting.delegate = g 
greeting() //执行后, 对象g的message和greeter被赋值

println g.message
println g.greeter

List

声明

class GroovyListDeclaration {
    static main(args) {
        def cartoons = []
        cartoons[0] = 'Regular Show'
        cartoons[1] = 'Adventure Time'
        println cartoons // [Regular Show, Adventure Time]
         
        def cartoonsWithInitialItems = ['The Amazing World of Gumball', 'Johnny Bravo']
        println cartoonsWithInitialItems // [The Amazing World of Gumball, Johnny Bravo]
         
        def cartoonsWithDefault = ['Johnny Test', 'Batman', 'Scooby Doo'].withDefault { 'Smurfs' }
        println cartoonsWithDefault[1] // Batman
        println cartoonsWithDefault[4] // Smurfs
    }
}

输出:
[Regular Show, Adventure Time]
[The Amazing World of Gumball, Johnny Bravo]
Batman
Smurfs

添加元素

class GroovyListAddItems {

    static main(args) {
        def cartoons = ['Regular Show', 'The Amazing World of Gumball']
        cartoons.push('Adventure Time') //add the item at the end.
        cartoons[3] = 'Batman'
        cartoons << 'Smurfs' //adds the item at the end.
        println cartoons // [Regular Show, The Amazing World of Gumball, Adventure Time, Batman, Smurfs]

        //添加item,但是不改变原有的list.
        println cartoons.plus(4, 'Scooby Doo')

        def cartoonsWithPlus = cartoons.plus(2, 'Scooby Doo')
        println cartoonsWithPlus // [Regular Show, The Amazing World of Gumball, Scooby Doo, Adventure Time, Batman, Smurfs]

        cartoons.add(0, 'Johnny Test')
        println cartoons // [Smurfs, Regular Show, The Amazing World of Gumball, Adventure Time, Batman, Johnny Test]

        cartoons.addAll(2, ['Tom and Jerry', 'Uncle Grandpa']) // [Smurfs, Regular Show, Tom and Jerry, Uncle Grandpa, The Amazing World of Gumball, Adventure Time, Batman, Smurfs]
        println cartoons
    }

}

输出:
[Adventure Time, Regular Show, The Amazing World of Gumball, Batman, Smurfs]
[Adventure Time, Regular Show, The Amazing World of Gumball, Batman, Scooby Doo, Smurfs]
[Adventure Time, Regular Show, Scooby Doo, The Amazing World of Gumball, Batman, Smurfs]
[Johnny Test, Adventure Time, Regular Show, The Amazing World of Gumball, Batman, Smurfs]
[Johnny Test, Adventure Time, Tom and Jerry, Uncle Grandpa, Regular Show, The Amazing World of Gumball, Batman, Smurfs]

删除元素

使用remove()、pop()方法

class GroovyListRemoveItems {
 
    static main(args) {
        def cartoons = ['Regular Show', 'The Amazing World of Gumball', 'Adventure Time']
        def poppedElement = cartoons.pop() 
        println poppedElement // Adventure Time
        println cartoons // [Regular Show, The Amazing World of Gumball]
         
        cartoons.remove(0)
        println cartoons // [The Amazing World of Gumball]
         
    }
 
}

元素查找

find()、findAll()、findIndexOf()、findLastIndexOf()。

class GroovyLookupItems {

    static main(args) {
        def cartoons = [
                'Regular Show',
                'The Amazing World of Gumball',
                'Adventure Time',
                'Uncle Grandpa',
                'Batman',
                'Scooby Doo'
            ]
        def scoobyDoo = cartoons.find { it == 'Scooby Doo' } //查找第一个等于'Scooby Doo'的元素.
        println scoobyDoo // Scooby Doo

        def cartoonNamesWithSizeGreaterThan12 = cartoons.findAll { it.size() > 12 } //查找所有长度>12的元素列表.
        println cartoonNamesWithSizeGreaterThan12 // [The Amazing World of Gumball, Adventure Time, Uncle Grandpa]

        def cartoonNamesWithSizeGreaterThan15 = cartoons.findAll { cartoon -> cartoon.size() > 15 } //自定义参数名称.
        println cartoonNamesWithSizeGreaterThan15 // [The Amazing World of Gumball]

        def cartoonsFoundWithRegex = cartoons.findAll { it =~ /an/ }
        println cartoonsFoundWithRegex // [Uncle Grandpa, Batman]

        def cartoonIndexList = cartoons.findIndexOf { it =~ /^A/ }
        println cartoonIndexList // 2

        def cartoonIndexListWithStartPoint = cartoons.findIndexOf(4) { it =~ /^A/ }
        println cartoonIndexListWithStartPoint // -1

        def cartoonLastIndex = cartoons.findLastIndexOf { it.size() > 10 }
        println cartoonLastIndex // 3
    }

}

输出:
Scooby Doo
[The Amazing World of Gumball, Adventure Time, Uncle Grandpa]
[The Amazing World of Gumball]
[Uncle Grandpa, Batman]
2
-1
3

元素拆分

class GroovyListSplit {
     
    static main(args) {
        def cartoons = [
                'Regular Show',
                'The Amazing World of Gumball',
                'Adventure Time',
                'Uncle Grandpa',
                'Batman'
            ]
         
        def cartoonsSplitListWithTwoCartoonEach = cartoons.collate(2)
        println cartoonsSplitListWithTwoCartoonEach // [[Regular Show, The Amazing World of Gumball], [Adventure Time, Uncle Grandpa], [Batman]]
         
        def cartoonsSplitListWithThreeCartoonEach = cartoons.collate(3)
        println cartoonsSplitListWithThreeCartoonEach // [[Regular Show, The Amazing World of Gumball, Adventure Time], [Uncle Grandpa, Batman]]
         
        def cartoonsSplitListWithoutRemainder = cartoons.collate(2, false)
        println cartoonsSplitListWithoutRemainder // [[Regular Show, The Amazing World of Gumball], [Adventure Time, Uncle Grandpa]]
    }
 
}

输出:
[[Regular Show, The Amazing World of Gumball], [Adventure Time, Uncle Grandpa], [Batman]]
[[Regular Show, The Amazing World of Gumball, Adventure Time], [Uncle Grandpa, Batman]]
[[Regular Show, The Amazing World of Gumball], [Adventure Time, Uncle Grandpa]]

计数(Count)

count()、size()函数.

class GroovyListCount {
     
    static main(args) {
        def cartoons = [
                'Regular Show',
                'The Amazing World of Gumball',
                'Adventure Time',
                'Regular Show',
                'Adventure Time',
                'Adventure Time'
            ]
        def cartoonCount = cartoons.size()
        println cartoonCount // 6
         
        def advTimeCount = cartoons.count('Adventure Time')
        println advTimeCount // 3
         
        def regShowCount = cartoons.count('Regular Show')
        println regShowCount // 2
    }
}

应用(Apply)

class GroovyListApply {
         
    static main(args) {
        def self = new GroovyListApply()
        def cartoons = [ 
                'Regular Show',
                'The Amazing World of Gumball',
                'Adventure Time'
            ]                                                                                                                     
        def cartoonsWithUpperCase = cartoons*.toUpperCase() //*表示对list的每一个元素执行toUpperCase()方法
        println cartoonsWithUpperCase // [REGULAR SHOW, THE AMAZING WORLD OF GUMBALL, ADVENTURE TIME]
    
        //对list的每一个元素应用uc()方法.
        def cartoonStartsAToUppercase = cartoons.collect { cartoon -> self.uc(cartoon) }
        println cartoonStartsAToUppercase // [Regular Show, The Amazing World of Gumball, ADVENTURE TIME]
    }   
 
    def uc(String cartoon) {
        if (cartoon =~ /^A/ ) cartoon.toUpperCase()
        else cartoon
    }   
}

输出:

上一篇 下一篇

猜你喜欢

热点阅读