3

鉴于:

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 的问题......

4

2 回答 2

6

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

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

processFruit(fruitList, this.&applePicker)

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

def applePicker = { FruitBasket f -> return f.getApples()    }
于 2012-07-24T15:32:38.540 回答
1

您正在传递applePickerprocessFruit,但它是一种方法。你只能通过这种方式传递闭包。像这样重新定义applePicker为闭包:

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

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

processFruit(fruitList, this.&applePicker)
于 2012-07-24T15:35:05.820 回答