user1866924
user1866924

Reputation: 431

How to return from a method that's calling a closure

I have a closure that I'm passing into a method(doExecute). I'd like to return from the calling method(getResellableState) if the shouldExecute variable in the doExecute method is passed a value of true.

I understand that a return inside a closure returns only from the closure, not from the method that called it, so I'm trying to understand how to return from the getResellableState method that called the closure.

Here's the code I'm trying to return from:

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)
    }
    ...
}

Here's the deExecute method:

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

Any help on this would be greatly appreciated. Thanks!

Upvotes: 0

Views: 101

Answers (2)

Roger Glover
Roger Glover

Reputation: 3266

How about something like this:

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
    }
    ...
}

Upvotes: 0

Will
Will

Reputation: 14559

1. Return some signal

The getResellableState needs to know whether it should keep executing the method or not, thus you need some kind of signalling:

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. Throw an exception

Your doExecute may throw an exception to stop the flow, but note this also needs proper handling

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 }
    })
    ...
}

Upvotes: 1

Related Questions