繁体   English   中英

Groovy 闭包返回值到变量

[英]Groovy closure return of value to variable

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

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

#! /usr/env/groovy

def matchFiles = { match ->
    new File(".").eachFile() {
        if (it.name =~ match) {
           println it
       }
    }
}

matchFiles('.groovy') ./g.groovy打印到屏幕上。

但我想在变量中捕获闭包的 output 并在其他地方使用它,例如

def fileMatches = matchFiles('.groovy')

但无法弄清楚这一点。

尝试更改println itreturn it然后运行

def fileMatches = matchFiles('.groovy')
fileMatches.println { it }

但这会打印出类似g$_run_closure2@4b168fa9

非常感谢任何帮助,对于任何不正确的命名法感到抱歉,对于 Groovy 来说非常新

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

因此,您必须定义一个数组结果变量,您将在其中存储每个匹配的文件

然后在eachFile{...}闭包后返回这个result变量

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

println matchFiles(/.*/)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM