`
jamie.wang
  • 浏览: 340424 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

groovy简明教程(四)闭包

    博客分类:
  • Java
阅读更多

6. 闭包(Closure)

闭包其实就是一段代码,但他们又是封装成一个Closure对象。可以类比为java的内部类,或者更好的是C++中的函数对象又叫仿函数(functor)。

闭包使得groovy的代码看起来更简洁,精炼。另外闭包可以使得资源处理更为简便。

例如:

new File(/testfile.txt/).eachLine {println it} // eachLine handle file close automatically

 其中的it是闭包默认的变量名。

6.1 声明闭包

前面都是简单的在用的时候直接声明闭包,其实也可以将闭包复制给一个变量,便于多处使用,甚至引用一个已存在对象的方法。闭包也支持默认参数。

def linePrinter = {println it}  // assign to a variable
linePrinter('this line') // call

class Foo {
    void bar(int value) {
        println "call int bar(int value), with params: $value"
    }
    void bar(List lst) {
        println "call int bar(List lst), with params: $lst"
    }
    void bar(int x, int y) {
        println "call int bar(int x, int y), with params: $x, $y"
    }
}

Foo foo = new Foo()
foo.bar(10) // normal call
Closure cls = foo.&bar // reference to foo
cls(3) // call by overload detected
cls([1,5,7])
cls(1,2)

def benchmark(repeat, Closure alg) {
    start = System.currentTimeMillis();
    repeat.times { alg(it) }
    return System.currentTimeMillis() - start
}

slow = benchmark(10000) { (int) it / 2 }
fast = benchmark(10000, { it.intdiv(2) })

// intdiv is faster than /
System.out.println("slow - fast = " + (slow - fast)) // output: slow - fast = 20

// default value
def inc = { x, i = 1 -> return x + i }
println inc(3) // output: 4
println inc(5, 2) // output: 7

6.2 闭包自身的方法

还记得C++的函数适配器吗?groovy也提供了这样的方法为Closer:curry(),可接受一个或多个参数。

之前已经看到了isCase方法,以进行分类。

def multiply = { x, y -> return x * y }
multiply.getParameterTypes().size() // result: 2
def double_ = multiply.curry(2)
println double_(3) // output: 6

[1, 2, 8, 7, 3].grep { it % 2 == 0 } // result: [2, 8]
switch(8) {
    case { it > 3 } : println "> 3" // output: > 3
}

6.3 从闭包返回结果

闭包有两种返回结果的方式:

a. 返回最后一个表达式执行的结果,在这种情况下return是可以省略的;

b. 从闭包的任何地方返回,注意这种返回的意思是,本次计算结束,也就意味着如果闭包用在循环中,下次的循环的元素将继续被调用;

 

[1, 2, 3].collect { it * 2 } // same as: return it * 2,result: [2, 4, 6]
[1, 2, 3].collect {
    if ( it % 2 == 0) return it * 2 // end current computing
    return it
} // result: [1, 4, 3]

6.4 闭包的变量作用域

 关于变量的作用域,理解内部类就很容易理解了。我直接引用书上的一个例子,因为想不出更好的例子了。

注意:书上的一个错误:

class Mother {
    int field = 1
    int foo() {
        return 2
    }
    Closure birth (param) {
        def local = 3
        def closure = { caller ->
            [ this, field, foo(), local, param, caller, owner ] // error in book: this.owner
        }
        return closure
    }
}

Mother julia = new Mother()
closure = julia.birth(4)
context = closure.call(this)
println context[0] == julia // output: ture

println context[1..4] // output: [1, 2, 3, 4]
println context[5] instanceof Script // output: true
println context[6] == julia // output: true

firstClosure = julia.birth(4)
secondClosure = julia.birth(4)
println firstClosure.is(secondClosure) // output: false

 特别要注意到是最后一个输出false,每次调用birth都生成了一新的Closure对象。

 

分享到:
评论

相关推荐

    Groovy入门教程.doc

    Groovy 教程。简单的groovy教程。

    Groovy入门教程

    Groovy入门教程 Groovy是一种基于JVM的敏捷开发语言,它结合了Python、Ruby和Smalltalk的许多强大的特性,Groovy 代码能够与 Java 代码很好地结合,也能用于扩展现有代码。由于其运行在 JVM 上的特性,Groovy 可以...

    Groovy入门教程[参照].pdf

    Groovy入门教程[参照].pdf

    groovy(10)-闭包委托策略1

    groovy(10)-闭包委托策略 /*闭包的三个重要变量:this,owner,delegate区别在于:this代表闭包定义处最近的对象(不包含闭包),ow

    groovy基础教程源码,很全面

    groovy基础教程源码,很全面tjureykjetyukmjyteytdeyhnjfgnjsfdghfdxhgsffgv bnvbn

    精通 Groovy 中文教程

    精通groovy ghy根据IBM教程整理 不可多得的好东西

    Groovy语法系列教程之集合(六)【完结】.pdf

    本系列教程介绍Groovy编程语言的语法。Groovy的语法源自Java语法,但是通过特定类型对其进行了增强,并允许进行某些简化。

    groovy 1.7官方教程

    groovy 1.7官方教程。groovy is a super version of Java

    Groovy教程.7z

    Groovy 是一种基于Java平台的面向对象语言。Groovy 的语法和 Java 非常的相似,可以使用现有的 Java 库来进行 Groovy 开发。可以将它想像成 Java 语言的一种更加简单、表达能力更强的变体。

    Groovy 教程

    本教程适合于不熟悉 Groovy,但想快速轻松地了解其基础知识的 Java™ 开发人员。了解 Groovy 对 Java 语法的简化变形,学习 Groovy 的核心功能,例如本地集合、内置正则表达式和闭包。

    Groovy语法系列教程之注释.zip

    Groovy语法系列教程之注释.zip Groovy语法系列教程之注释.zip Groovy语法系列教程之注释.zip Groovy语法系列教程之注释.zip

    Groovy DSL

    Groovy 是基于Java的脚本语言。是Java语言扩展,因此可以与Java语言互相调用。在所有基于JVM虚拟机的语言中只有Scala可以媲美。使用Groovy可以快速灵活完成文本处理,数据库访问,XML处理等常见任务。研究表明,使用...

    Groovy中文教程.pdf

    你可能急着的编写一些Groovy 代码, 对吧? 好的, 首先,你必须安装Groovy. 在这章, 我将告 诉你如何快速安装 Groovy 并确保一切在你的系统上运行良好.

    [Groovy入门]第五讲.将流程控制语句与方法重构为闭包

    [Groovy入门]第五讲.将流程控制语句与方法重构为闭包

    Groovy中文教程

    OFBiz开发者装备系列:0005

    Groovy Script 入门

    Groovy Script 入门 Groovy 脚本入门

    Groovy中文版教程

    Groovy in action中文版,与java无缝集成的快速脚本语言

    apache-groovy-sdk-2.4.11

    了解 Groovy 对 Java 语法的简化变形,学习 Groovy 的核心功能,例如本地集合、内置正则表达式和闭包。编写第一个 Groovy 类,然后学习如何使用 JUnit 轻松地进行测试。借助功能完善的 Groovy 开发环境和使用技能,...

    Groovy教程学习资料宣贯.pdf

    Groovy教程学习资料宣贯.pdf

    Groovy语法系列教程之注释(一).pdf

    本系列教程介绍Groovy编程语言的语法。Groovy的语法源自Java语法,但是通过特定类型对其进行了增强,并允许进行某些简化。

Global site tag (gtag.js) - Google Analytics