stephansun对《Programming Groovy 2》的笔记(2)

stephansun
stephansun (认真你就输了...)

读过 Programming Groovy 2

Programming Groovy 2
  • 书名: Programming Groovy 2
  • 作者: Venkat Subramaniam
  • 副标题: Dynamic Productivity for the Java Developer
  • 页数: 350
  • 出版社: Pragmatic Bookshelf
  • 出版年: 2013-7-22
  • 第88页

    勘误

    def clone = closure.clone() clone.delegate = handler clone() we can perform those three steps in one shot using a special with() method: handler.with closure
    引自第88页

    原文这么描述不太严谨,这句话字面上的意思是 1.

    handler.with closure

    和 2.

    def clone = closure.clone()
    clone.delegate = handler
    clone()

    是等价的,但实际上代码1运行的结果是 f1 of Script called... f2 of Handler called... 代码2运行的结果是 f1 of Handler called... f2 of Handler called...

    2013-11-26 18:46:59 回应
  • 第88页
    In the previous example, we set the `delegate` property on a closure. This has side effects, especially if the closure can be used in other functions or in other threads. If we're absolutely sure that the closure is not used elsewhere, we can set the `delegate`. If it is used elsewhere, avoid the side effect -- clone the closure, set the delegate on the clone, and use the clone. Groovy provides a convenient method to achieve this. Rather than performing: def clone = closure.clone() clone.delegate = handler clone() we can perform those three steps in on shot using a special `with()` method: handler.with closure
    引自第88页
    2014-06-25 20:13:42 回应