user3240644
user3240644

Reputation: 2281

How to return a value from Closure into a method

I'm obviously doing it wrong but isn't it possible for callPrint() to use the return value from the closure? How can I correctly pass the return value of a Closure into a method?

void callPrint(def num){
    println "${num}";
}

callPrint{return 5}; //does not print

Thanks.

Regards, John

Upvotes: 2

Views: 3803

Answers (1)

jalopaba
jalopaba

Reputation: 8129

You have to pass a closure to callPrint method and actually call it inside it:

void callPrint(closure){
    println closure.call()
}

callPrint{return 5}

def hello = { return 'Hello' }

callPrint(hello)

It prints:

5
Hello

Upvotes: 3

Related Questions