zoukankan      html  css  js  c++  java
  • Groovy闭包深入学习 [203] 一直都有新高度 ITeye技术网站

    Groovy闭包深入学习 - [203] 一直都有新高度 - ITeye技术网站

    闭包



    1. 定义和执行闭包


    Java代码  收藏代码
    1. def one = { num1, num2 ->  
    2.     println "param is: $num1 & $num2"  
    3. }  
    4. one(23)       // 简便写法。输出 param is: 2 & 3  
    5. one 23        // 省略()的等效写法  
    6.   
    7. one.call(23// 使用call方法  
    8. one.call 23  // 省略()等效写法  


    注意:

    • a) 闭包自身的定义写法。在参数与具体代码执行端间的分隔符是->,老版本的是|
    • b) 使用call方法,或简便写法。
    • c) 由于groovy可省略(),而引发的众多等效写法。
    • d) 单参数,可省略书写参数,在闭包内使用it变量引用参数。




    2. 闭包作为参数返回


    Java代码  收藏代码
    1. def makeClosure(name) {  
    2.     return {  
    3.         println "Hello ${name}"  
    4.     }  
    5. }  
    6.   
    7. println makeClosure(‘World’) // 请问输出结果?   


    3. 闭包作为参数传递


    Java代码  收藏代码
    1. def run(closure) {  
    2.     closure.call()  
    3. }  
    4.   
    5. one = { println 'Hello, World!' }  
    6.   
    7. run(one)  




    4. 闭包使用外部变量


    Java代码  收藏代码
    1. class OneClosure {  
    2.     def static execute(closure) {  
    3.         def word = 'Cool' // !!! 注意不使用def的输出结果,理解方式使用引用  
    4.         closure('Grails')  
    5.     }  
    6.       
    7.     public static void main(args) {  
    8.         def word = 'Hello'  
    9.           
    10.         def two = {param -> println "${word} ${param}"}  
    11.         two('Groovy'// 输出 Hello Groovy  
    12.           
    13.         word = 'Wow'  
    14.         two('Java'// 输出 Wow Java  
    15.           
    16.         OneClosure.execute(two) // 输出 Wow Grails,而不是Cool Grails  
    17.     }  
    18. }  


    注意:

    • a) 闭包可使用(引用)闭包外部定义的变量
    • b) 变量的定义必须在闭包的上面,否则有groovy.lang.MissingPropertyException异常。
    • c) 注意在代码标记出,如果不使用def的输出差异。具体解释可使用引用来理解。在一个闭包被定义后,使用的是闭包定义所在的外部对象,对于使用的外部对象的引用一直都不会改变(无论是否被作为参数传递)。




    5. 使用闭包实现单方法接口


    Java代码  收藏代码
    1. interface Test {  
    2.     def one()  
    3. }  
    4.   
    5. def test = {println 'one'} as Test  
    6.   
    7. test.one()  




    • a) 使用关键字as




    6. 使用闭包实现多方法接口


    Java代码  收藏代码
    1. interface Test {  
    2.     def one()  
    3.     def two()  
    4. }  
    5.   
    6. def test = [  
    7.     one: {println 'one'},  
    8.     two: {println 'two'}  
    9.     ] as Test  
    10.   
    11. test.one()  
    12. test.two()  
    • a) 使用关键字as
    • b) 使用Map, key为接口名,value为闭包
    分享到:

  • 相关阅读:
    nginx 域名跳转一例~~~(rewrite、proxy)
    军哥 LNMP 常见问题
    Zabbix安装
    PHP远程连接mysql
    Zend Studio 下载
    军哥LNMP优化
    网络流量监控分析工具 Ntopng 安装
    Linux VPS禁止某个IP访问
    DDoS deflate
    MySQL数据库的优化
  • 原文地址:https://www.cnblogs.com/lexus/p/2650922.html
Copyright © 2011-2022 走看看