如何使用Groovy Closure选择特定字段

时间:2012-07-24 15:20:02

标签: groovy closures

假设:

class FruitBasket {
    int apples = 0
    int oranges = 0
}

我需要从每个FruitBasket中挑选苹果。这项工作需要在processFruit中完成:

def processFruit(list, picker) {
    list.each {
        println "processing " + picker(it)
    }
}

def processAll() {
    List fruitList = [
        new FruitBasket("apples": 2, "oranges": 4),
        new FruitBasket("apples": 3, "oranges": 5)
    ]

    processFruit(fruitList, applePicker)
}

def applePicker(FruitBasket f) {
    return f.getApples()    
}

但它正在抱怨@ runtime

No such property: applePicker for class: FooTest

可能是关闭FruitBasket arg的问题...

2 个答案:

答案 0 :(得分:6)

在该代码中,applePicker是一个方法,而不是闭包。

您可以使用方法句柄将方法作为参数传递,如下所示:

processFruit(fruitList, this.&applePicker)

或者将其更改为实际的闭包:

def applePicker = { FruitBasket f -> return f.getApples()    }

答案 1 :(得分:1)

您正在将applePicker传递给processFruit,但这是一种方法。你只能通过这种方式传递闭包。将applePicker重新定义为闭包,如下所示:

applePicker = { FruitBasket f ->
    return f.getApples()
}

或者在调用processFruit时将方法转换为闭包:

processFruit(fruitList, this.&applePicker)