Groovy闭包将值返回到变量

Groovy闭包将值返回到变量,groovy,closures,Groovy,Closures,非常基本的问题,但我找不到答案: 我在文件g.groovy中有以下代码,它在打印输出中起作用: #! /usr/env/groovy def matchFiles = { match -> new File(".").eachFile() { if (it.name =~ match) { println it } } } matchFiles('.groovy')将/g.groovy打印到屏幕上 但是我想在一个变量中

非常基本的问题,但我找不到答案:

我在文件
g.groovy
中有以下代码,它在打印输出中起作用:

#! /usr/env/groovy

def matchFiles = { match ->
    new File(".").eachFile() {
        if (it.name =~ match) {
           println it
       }
    }
}
matchFiles('.groovy')
/g.groovy
打印到屏幕上

但是我想在一个变量中捕获闭包的输出,并在其他地方使用它,例如

def fileMatches = matchFiles('.groovy')
但我无法理解这一点

尝试将
println-it
更改为
返回它
,然后运行

def fileMatches = matchFiles('.groovy')
fileMatches.println { it }
但这会打印出类似于
g$\u run的内容_closure2@4b168fa9


非常感谢您提供的任何帮助,对于任何不正确的命名,我们深表歉意,Groovy非常新

根据名称
matchFiles
我假设您希望返回所有匹配的文件

因此,必须定义一个数组结果变量,用于存储每个匹配的文件

然后在
eachFile{…}
closure之后返回这个
result
变量

def matchFiles = { match ->
    def result=[]
    new File(".").eachFile {
        if (it.name =~ match) {
            result.add(it)
        }
    }
    return result
}

println matchFiles(/.*/)