简体   繁体   中英

groovy .. passing closures as parameter to another closure

By way of example ..

def data = [1,2,3,4,5,6,7]

def someFilter = {it-> it % 2 == 0}

def newData = data.findAll{it,someFilter ->
   someFilter(it)
}

newData

gives me an error ..

The current scope already contains a variable of the name someFilter at line: 5, column: 27

is it possible to pass a closure (maybe anonomously) to another closure ?

Thanks

You can pass closures. I believe this is what you had intended:

def data = [1,2,3,4,5,6,7]

def someFilter = {it-> it % 2 == 0}

def newData = data.findAll someFilter 
newData // results in [2, 4, 6]

To pass a closure anonymously,

def newData = data.findAll { it % 2 == 0 }

The it variable is implicitly defined for the first argument passed to the closure; you only need to use the arrow syntax for multiple variables or for giving the first argument a different name, eg

def newData = data.findAll { nbr -> nbr % 2 == 0 }

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