簡體   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