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

  • 相关阅读:
    JWT(JSON WEB TOKEN) / oauth2 / SSL
    Guice 学习
    九 fork/join CompletableFuture
    二 lambda表达式
    IDEA 热部署 + 下载jar包放到maven中
    微服务学习一 微服务session 管理
    一 Optional
    八 线程池(待续)
    七 内置锁 wait notify notifyall; 显示锁 ReentrantLock
    六 多线程问题
  • 原文地址:https://www.cnblogs.com/eastson/p/2519411.html
Copyright © 2011-2022 走看看