Groovy闭包

task helloClosure << {
  //使用我们自定义的闭包
  customEach{
        println it
  }

}




def customEach(closure){
  //模拟一个有10个元素的集合,开始迭代
  for (int i in 1..10){
   closure(i)
  }
}

  

task helloMapClosure << {
        //多个参数
        eachMap{k,v->
        println "${k} is ${v}"
}
}

def eachMap(closure){
  def map1 = ['name':'张三','age':18]
  map1.each{
    closure(it.key,it.value)
  }
}

  

task helloDelegate << {
  new Delegate().test {
    println "thisObject:${thisObject.getClass()}"

    println "owner:${owner.getClass()}"
    println "delegate:${delegate.getClass()}"
    method1();
    it.method1();
  }
}

def method1(){
  println "Context this:${this.getClass()} in root"
  println "method1 in root"
}

class Delegate {
  def method1(){
    println "Delegate this: ${this.getClass()} in Delegate"
    println "method1 in Delegate"
  }
  def test(Closure<Delegate> closure){
    closure(this);
  }
}

  

posted on 2018-10-15 17:32  endian11  阅读(83)  评论(0编辑  收藏  举报

导航