zoukankan      html  css  js  c++  java
  • GString惰性求值

    1. 当对一个GString实例求值时,如果其中包含一个变量,该变量的值会被简单地打印到一个Writer,通常是一个StringWriter。然而,如果GString中包含的是一个闭包,而非变量,该闭包就会被调用。如果闭包接受一个参数,GString会把Writer对象当做一个参数发送给它。如果闭包不接受任何参数,GString会简单地调用该闭包,并打印我们想返回Writer的结果。如果闭包接受的参数不止一个,调用则会失败,并抛出一个异常。
    2. 如果希望改变表达式中使用的引用,而且希望它们的当前值被用于惰性求值中,请必须记住,不要再表达式中直接替换他们,而要使用一个无参闭包。

    例子对比:
    companyClosure = {-> company}
    priceClosure = {-> price}
    quote = "Today ${companyClosure} stock closed at ${priceClosure}"
    stocks = [Apple : 663.01 ,Microsoft : 30.95]
    stocks.each{key,value->
    company = key
    price = value
    println quote
    }

    结果输出:

    Today Apple stock closed at 663.01
    Today Microsoft stock closed at 30.95

    例子对比:
    price = 684.71
    company = 'Google'
    qutoe = "Today $company stock closed at $price"
    println qutoe

    stocks = [Apple : 663.01 ,Microsoft : 30.95]
    stocks.each{key,value->
    company = key
    price = value
    println qutoe
    }

    结果输出:

    Today Google stock closed at 684.71
    Today Google stock closed at 684.71
    Today Google stock closed at 684.71

  • 相关阅读:
    sql: update from
    sql: 查询,select
    english: 遭遇
    sql: sybase与oracle中insert into select和select into的用法
    lcd参数解释及刷新率计算,LCD时序
    Camera Binning Mode
    页框分配器【转】
    (一)洞悉linux下的Netfilter&iptables:什么是Netfilter?
    网络中的NAT模式
    组播、单播、多播
  • 原文地址:https://www.cnblogs.com/jsersudo/p/10340594.html
Copyright © 2011-2022 走看看