我是靠谱客的博主 现实鸭子,这篇文章主要介绍Groovy天哪:闭包可写,现在分享给大家,希望可以做个参考。

在上一篇文章中,我们了解了Writable接口以及GString实现如何实现此接口。 在Groovy中,我们还可以将闭包用作Writable接口的实现。 Closure类具有asWritable()方法,该方法将返回带有writeTo()方法实现的闭包版本。 用作writeTo()方法的参数的Writer对象将作为参数传递给闭包。 asWritable()方法还为闭包添加了toString()实现,以将闭包的结果作为String

在下面的代码中,我们编写了一个示例make()方法。 make()方法返回Writable闭包。 仅在调用writeTo()toString()方法时执行关闭。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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天哪内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(48)

评论列表共有 0 条评论

立即
投稿
返回
顶部