使用条件日志关闭 [英] Closure with conditional logging
问题描述
我有这样的功能:
private downloadAllFiles() {
sftpRetriever.listFiles().findAll {
filter.isResponse(it) || filter.isResponseTurned(it)
}.each { String fileName ->
log.info 'Downloading file: {}', fileName
sftpRetriever.downloadFile(fileName)
log.info 'File downloaded'
removeRemoteFile(fileName)
}
}
我正在寻找一个简单的方法来修改这个闭包里面的函数如果findAll的size()是0,它将只记录没有更多的文件要下载和.each将不会被执行。有没有任何简单的方法来使它在单闭合?如果我把它分成几个部分,但试图在这里学习闭包并提高我的表达力,这真的是简单的任务:)提前为您的帮助。
I am looking for a simple way of modyfing this closure inside of that function so if the size() of findAll is 0 it will simply log 'No more files to download' and .each won't be executed. Is there any simple way to make it in single closure? It is really simply task if I divide it in several parts, but trying to learn closures here and improve my expressiveness :) Thank you in advance for your help.
推荐答案
看看下面的生物:)它的工作原因是 each
返回调用它的集合(+ elvis操作符和相当不错的Groovy的真理评估):
Take a look at creature below :) It works due the fact that each
returns the collection on which it's invoked (+ elvis operator and quite nice Groovy's truth evaluation):
def printContents(Collection collection) {
collection.each {
println it
} ?: println('Collection is empty')
}
printContents([1,2,'hello'])
printContents([])
您也可以使用元编程添加由Steinar提供的方法。在首次使用之前必须将其添加到 metaClass
,但是您将避免尝试创建扩展模块:
You can also use metaprogramming to add the method provided by Steinar. It must be added to metaClass
before first use but you'll avoid an effort to make extension module:
Collection.metaClass.doIfEmpty { Closure ifEmptyClosure ->
if (delegate.empty) {
ifEmptyClosure()
}
return delegate
}
def printContents(Collection collection) {
collection.doIfEmpty {
println "Collection is empty"
}.each {
println it
}
}
printContents([1,2,'hello'])
printContents([])
这篇关于使用条件日志关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!