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