groovy-闭包

2019-01-14  本文已影响4人  望月成三人

定义和执行闭包

def one = { num1, num2 ->
    println "param is: $num1 & $num2"
}
one(2, 3)       // 简便写法。输出 param is: 2 & 3
one 2, 3        // 省略()的等效写法

one.call(2, 3) // 使用call方法
one.call 2, 3  // 省略()等效写法

闭包作为参数返回

def makeClosure(name) {
    return "Hello ${name}"

}

println makeClosure("World")

闭包作为参数传递

def run(closure) {
    closure.call()
}

one = { println 'Hello, World!1' }

run(one)

闭包使用外部变量

class OneClosure {
    def static execute(closure) {
        def word = 'Cool' // !!! 注意不使用def的输出结果,理解方式使用引用
        closure('Grails')
    }
    
    public static void main(args) {
        def word = 'Hello'
        
        def two = {param -> println "${word} ${param}"}
        two('Groovy') // 输出 Hello Groovy
        
        word = 'Wow'
        two('Java') // 输出 Wow Java
        
        OneClosure.execute(two) // 输出 Wow Grails,而不是Cool Grails
    }
}

注意:

使用闭包实现接口

interface Test {
    def one()
}

def test = {println 'one'} as Test

test.one()
interface Test {
    def one()
    def two()
}

def test = [
    one: {println 'one'},
    two: {println 'two'}
    ] as Test

test.one()
test.two()

delegate委托的用法

狗爸爸让老猫帮忙照看他的狗儿子玩游戏。

class Dog{
    def play = {
        "wang wang!"
    }
    def childmind = {
        println delegate.play();
    }
}
class Cat {
    def play = {"mi mi !"}
}
def dog = new Dog()
def cat = new Cat()
dog.childmind()
dog.childmind.delegate  = cat;
dog.childmind()

递归

def foo(n) {
    return {n += it}
}
def t = foo(1)
println(t(2)) //3
println(t(3)) //6

上一篇下一篇

猜你喜欢

热点阅读