zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    数字精确运算BigDecimal经常用法
    C3P0数据库连接池使用
    Theano学习笔记(四)——导数
    Leetcode--Merge Intervals
    1191 数轴染色
    P1021 邮票面值设计
    P1032 字串变换
    P1294 高手去散步
    P1832 A+B Problem(再升级)
    P1332 血色先锋队
  • 原文地址:https://www.cnblogs.com/eastson/p/2519411.html
Copyright © 2011-2022 走看看