zoukankan      html  css  js  c++  java
  • Groovy闭包

    定义

    闭包(Closure)是一种数据类型,它代表一段可执行的代码。它可以作为方法的参数,或者返回值,也可以独立运行,定义如下:

      def xxx = {parameters -> code}  
      def xxx = {无参数,纯code}

    如我们定义一个名字叫add的闭包,如下:

    def add = { a, b -> a + b }
    println("3+5=" + add(3, 5))

    如果闭包没有定义参数,那边它隐含一个参数it,类似Java中的this,假设你的闭包不需要接受参数,但是还是会生成一个隐式参数it,只不过它的值为null,也就是说,闭包至少包含一个参数。

    def greeting = { "Hello Closure, $it!" }
    println(greeting('Jack'));
    def getStr = { return "abcd:$it" }
    println(getStr())

     输出如下:

    Hello Closure, Jack!
    abcd:null

    当闭包作为闭包或方法的最后一个参数,可以将闭包从参数圆括号中提取出来接在最后,如果闭包是唯一的一个参数,则闭包或方法参数所在的圆括号也可以省略。

    def run = { int a, Closure c -> c(a) }
    println(run(5) { y -> y * 3 })
    def run2 = { Closure c -> c.call() }
    run2 {
        println("jack:Closure")
    }

     输出如下:

    15
    jack:Closure

    如果闭包的参数声明中没有list,那么传入参数可以设置为list,里面的参数将分别传入闭包参数。

    def list = [1, 2, 3]
    def sum= {a, b, c-> a + b + c}
    println(sum(list))

    输出如下:

    6

    闭包是可嵌套的

    def gcd
    gcd={ m,n-> m%n==0? n: gcd(n,m%n) }
    println(gcd(28,35))

    输出如下:

    7

  • 相关阅读:
    二叉树
    队列
    python3使用pdfminer3k解析pdf文件
    得到手机版新闻解析
    python连接redis并插入url
    Python使用requirements.txt安装类库
    (1366, "Incorrect string value: '\xF3\xB0\x84\xBC</...' for column 'content' at row 1")
    mysql中Incorrect string value乱码问题解决方案
    mysql命令
    requests ip代理池单ip和多ip设置方式
  • 原文地址:https://www.cnblogs.com/rainboy2010/p/8997671.html
Copyright © 2011-2022 走看看