• Groovy系列 闭包Closure


    闭包是什么?看看Groovy Documentation里面的定义:Closures are similar to Java's inner classes, except they are a single method which is invokable, with arbitrary parameters. 

     

    我自己的理解:闭包就是一个method变量,可以有很多的参数。

    简单的闭包实例:

    def closure = { param -> println("hello ${param}") }
    closure.call("world!")
    
    closure = { greeting, name -> println(greeting + name) }
    closure.call("hello ", "world!")

    从上面的例子可以看出:

    • 闭包的定义放在{}中间。
    • 参数放在->符号的左边,语句放在->符号的右边。如果有多个参数,参数之间用逗号分割。
    • 使用call()可以执行闭包。

    如果在->符号的左边没有指定参数,Groovy会默认一个it的参数:

    def closure = { println "hello " + it }
    closure.call("world!")

    使用闭包可以很方便的处理集合:

    [1, 2, 3].each({item -> println "${item}-"})
    ["k1":"v1", "k2":"v2"].each({key, value -> println key + "=" + value})

    如果闭包是某个方法调用的最后一个参数,则闭包的定义允许放在方法调用圆括号的外边:

    def fun(int i, Closure c) {
      c.call(i)
    }
    
    // put Closure out of ()
    [1, 2, 3].each() { item -> print "${item}-" } // 1-2-3-
    fun(123) { i -> println i } // 123
    
    // omit ()
    [1, 2, 3].each ({ item -> print "${item}-" }) // 1-2-3-
    
    // omit enclosing ()
    [1, 2, 3].each { item -> print "${item}-" } // 1-2-3-
    
    // normal
    [1, 2, 3].each(({ item -> print "${item}-" })) // 1-2-3-
    
    // using the fun function to do the same thing
    [1,2,3].each {fun(it,{item -> print "${item}-"})} // 1-2-3-
    
    def closure = { i -> println i}
    
    //[1, 2, 3].each() closure // error. closure has been previously defined

    本文参考文档:http://groovy.codehaus.org/Quick+Start

  • 相关阅读:
    一个测试HTML Method的例子
    eXtplorer:在线管理网站文件的利器
    PHPXref:PHP文件交叉引用工具
    统计MySQL数据库大小
    PHP函数glob()
    PclZip:PHP压缩与解压缩
    PHP发送有附件的电子邮件[转]
    查找表中的主键
    CentOS6.4简单配置Cobar
    CentOS6.4 安装mysql cmake的参数说明
  • 原文地址:https://www.cnblogs.com/eastson/p/2519411.html
Copyright © 2020-2023  润新知