有什么方法可以将Groovy的collect方法与另一个迭代器函数结合使用吗? [英] Is there any way to leverage Groovy's collect method in combination with another iterator function?
问题描述
void eachDir(Closure closure)
当我使用 eachDir
时,我必须使用首先创建集合的详细方法并附加到它:
def collection = []
dir1.eachDir {dir - >
集合<< dir
}
有什么办法让它恢复到nice compact语法?我不知道任何惯用的做法,很好的谜语! = D
您可以尝试将 eachDir
或任何类似的函数传递给将收集其迭代的函数:
def collectIterations(fn){
def col = []
fn {
col<< it
}
col
}
现在你可以使用它:
def dir = new File('/ path / to / some / dir')
def subDirs = collectIterations(dir。& eachDir)
def file = new File('/ path / to / some / file')
def lines = collectIterations(file。& eachLine)
(最后一个例子相当于 只有在奖励积分时,您可以将此函数定义为 file.readLines()$ c
类中的方法:
Closure.metaClass.collectIterations = { - >
def col = []
delegate.call {
col<< it
}
col
}
def dir = new File('/ path / to / some / dir')
def subDirs = dir。 & eachDir.collectIterations()
def file = new File('/ path / to / some / file')
def lines = file。& eachLine.collectIterations()
更新:另一方面,您也可以这样做:
def col = []
someDir.eachDir col。& add
我认为这不太复杂,但它没有按照您的要求利用 collect
方法:)
For example, the groovy File class has a nice iterator that will filter out just directories and not files:
void eachDir(Closure closure)
When I use eachDir
, I have to use the verbose method of creating the collection first and appending to it:
def collection = []
dir1.eachDir { dir ->
collection << dir
}
Any way to get it back to the nice compact collect syntax?
I don't know of any "idiomatic" way of doing this, nice riddle! =D
You can try passing the eachDir
, or any similar function, to a function that will collect its iterations:
def collectIterations(fn) {
def col = []
fn {
col << it
}
col
}
And now you can use it as:
def dir = new File('/path/to/some/dir')
def subDirs = collectIterations(dir.&eachDir)
def file = new File('/path/to/some/file')
def lines = collectIterations(file.&eachLine)
(that last example is equivalent to file.readLines()
)
And only for bonus points, you may define this function as a method in the Closure
class:
Closure.metaClass.collectIterations = {->
def col = []
delegate.call {
col << it
}
col
}
def dir = new File('/path/to/some/dir')
def subDirs = dir.&eachDir.collectIterations()
def file = new File('/path/to/some/file')
def lines = file.&eachLine.collectIterations()
Update: On the other hand, you might also do:
def col = []
someDir.eachDir col.&add
Which I think is quite less convoluted, but it's not leveraging the collect
method as you requested :)
这篇关于有什么方法可以将Groovy的collect方法与另一个迭代器函数结合使用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!