def closer2 = { text -> println text //一个参数 } closer2('this is close2')
def closer3 = { //多个参数 name,age-> println "This is ${name},${age} yeas old" } closer3('zhangsan',20) 额外说明:groovy的这种将代码块赋值给变量的做法和JavaScript也有像,不过JavaScript的写法是var f = function(){} 2 delegate 其实delegate和java中的上下文类似,delegate将指定待执行代码的对象。类似于java中 的代码: interface Target{ voID surf(); } class Aoo implments Target{ public voID surf(){ System.out.println("Aoo surfing"); } } class Boo implemets Target{ public voID surf(){ System.out.println("Aoo surfing"); } private Target target; public Boo(){} public Boo(Target target){ this.target = target; } public voID invoke(){ target.surf(); } } groovy的delegate属性: class Net{ def work = { println 'Net is working' } def surf={ println 'Net is surfing' } }
class AdaptNet{
def work = { println 'AdaptNet is working' } def surf ={ println 'AdaptNet is surfing' } def invoke(closer){ closer.delegate = new Net() // closer.delegate = new AdaptNet()// close.surf将输出"AdaptNet is surfing" closer.surf()//将输出'Net is surfing work() } }
new AdaptNet().invoke{} 3闭包访问集合 def array =[1,2,3,4,5] array.each{ print it+' ' }
def maps = [name:'s1',age:10,score:85]
maps.each{ data-> print data.key+':'+data.value+' ' } 总结
以上是内存溢出为你收集整理的groovy入门4 闭包简介全部内容,希望文章能够帮你解决groovy入门4 闭包简介所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)