如何从调用闭包的方法返回

时间:2016-11-09 14:55:20

标签: groovy

我有一个关闭,我将其传递给方法(doExecute)。如果getResellableState方法中的shouldExecute变量传递的值为true,我想从调用方法(doExecute)返回。

我理解闭包内部的返回仅从闭包返回,而不是从调用它的方法返回,所以我试图理解如何从调用闭包的getResellableState方法返回。

这是我试图返回的代码:

ResellableState getResellableState(Ticket ticket) {
    int counter = 0
    doExecute(!isResellable(ticket.inventoryLineItem.inventoryAccess), counter) { int count ->
        return createResellableState(com.ticketfly.commerce.enums.ResellableState.FEATURE_DISABLED, count)
    }
    ...
}

这是deExecute方法:

private doExecute(boolean shouldExecute, int counter, block) {
    counter++
    if (shouldExecute) {
        block(counter)
    }
}

对此的任何帮助将不胜感激。谢谢!

2 个答案:

答案 0 :(得分:1)

1。返回一些信号

getResellableState需要知道它是否应继续执行该方法,因此您需要某种信令:

ResellableState getResellableState(Ticket ticket) {
    int counter = 0
    if (!doExecute(!isResellable(ticket.inventoryLineItem.inventoryAccess), counter) { int count ->
        return createResellableState(com.ticketfly.commerce.enums.ResellableState.FEATURE_DISABLED, count)
    }) {
        ...
    }
}

2。抛出异常

您的doExecute可能会抛出异常以阻止流程,但请注意这也需要正确处理

ResellableState getResellableState(Ticket ticket) {
    int counter = 0
    doExecute(!isResellable(ticket.inventoryLineItem.inventoryAccess), counter) { int count ->
        try {
            return createResellableState(com.ticketfly.commerce.enums.ResellableState.FEATURE_DISABLED, count)
        } catch (e) { throw e }
    })
    ...
}

答案 1 :(得分:0)

这样的事情怎么样:

ResellableState getResellableState(Ticket ticket) {
    int counter = 0
    def state = doExecute(!isResellable(ticket.inventoryLineItem.inventoryAccess), counter) { int count ->
        return createResellableState(com.ticketfly.commerce.enums.ResellableState.FEATURE_DISABLED, count)
    }
    if (state instanceof ResellableState) {
        return state
    }
    ...
}