概述
在上一篇文章中,我们了解了Writable
接口以及GString实现如何实现此接口。 在Groovy中,我们还可以将闭包用作Writable
接口的实现。 Closure
类具有asWritable()
方法,该方法将返回带有writeTo()
方法实现的闭包版本。 用作writeTo()
方法的参数的Writer
对象将作为参数传递给闭包。 asWritable()
方法还为闭包添加了toString()
实现,以将闭包的结果作为String
。
在下面的代码中,我们编写了一个示例make()
方法。 make()
方法返回Writable
闭包。 仅在调用writeTo()
或toString()
方法时执行关闭。
Writable make(Map binding = [:], Closure template) {
// Use asWritable() to make the closure
// implement the Writable interface.
def writableTemplate = template.asWritable()
// Assing binding map as delegate so we can access
// the keys of the maps as properties in the
// closure context.
writableTemplate.delegate = binding
// Return closure as Writable.
writableTemplate
}
// Use toString() of Writable closure.
assert make { Writer out -> out << "Hello world!" }.toString() == 'Hello world!'
// Provide data for the binding.
// The closure is not executed when the
// make method is finished.
final writable = make(user:'mrhaki', { out ->
out.println "Welcome ${user},"
out.print "Today on ${new Date(year: 114, month: 3, date: 4).format('dd-MM-yyyy')}, "
out.println "we have a Groovy party!"
})
// We invoke toString() and now the closure
// is executed.
final result = writable.toString()
assert result == '''Welcome mrhaki,
Today on 04-04-2014, we have a Groovy party!
'''
// Append contents to a file.
// NOTE: The leftShift (<<) operator on File is implemented
// in Groovy to use the File.append() method.
// The append() method creates a new Writer and
// invokes the write() method which
// is re-implemented in Groovy if the argument
// is a Writable object. Then the writeTo() method
// is invoked:
// Writer.write(Writable) becomes Writable.writeTo(Writer).
// So a lot of Groovy magic allows us to use the following one-liner
// and still the writeTo() method is used on Writable.
new File('welcome.txt') << writable
assert new File('welcome.txt').text == '''Welcome mrhaki,
Today on 04-04-2014, we have a Groovy party!
'''
用Groovy 2.2.2编写的代码
翻译自: https://www.javacodegeeks.com/2014/04/groovy-goodness-closure-as-writable.html
最后
以上就是现实鸭子为你收集整理的Groovy天哪:闭包可写的全部内容,希望文章能够帮你解决Groovy天哪:闭包可写所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复