【问题标题】:Groovy closure return of value to variableGroovy闭包将值返回给变量
【发布时间】:2020-04-06 14:23:47
【问题描述】:

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

我在文件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 更改为 return it 然后运行

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

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

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

【问题讨论】:

    标签: groovy closures


    【解决方案1】:

    根据名字matchFiles我假设你想返回所有匹配的文件

    所以,你必须定义一个数组结果变量来存储每个匹配的文件

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

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

    【讨论】:

      猜你喜欢
      • 2016-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-15
      相关资源
      最近更新 更多