简体   繁体   中英

Groovy closure return of value to variable

Very basic question but I cannot find an answer:

I have the below code in a file g.groovy , and it functions in printing output:

#! /usr/env/groovy

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

matchFiles('.groovy') prints ./g.groovy to screen.

But I want to capture the output of the closure in a variable and use it elsewhere, eg

def fileMatches = matchFiles('.groovy')

but cannot figure this out.

Tried changing println it to return it and then running

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

but this prints something like g$_run_closure2@4b168fa9

Any help is much appreciated, sorry for any incorrect nomenclature, very new to Groovy

according to the name matchFiles I assume you want to return all matched files

so, you have to define an array result variable where you are going to store each matched file

and then return this result variable after eachFile{...} closure

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

println matchFiles(/.*/)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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