Closures and Coroutines

Calling a function or method creates a new scope in a program’s execution sequence. We enter the function at one entry point (top). After we complete the method, we return to the caller’s scope.

Coroutines, on the other hand, support multiple entry points, each following the place of the last suspended call. We can enter a function, execute part of it, suspend, and go back to execute some code in the context or scope of the caller. We can then resume execution of the function from where we suspended. As Donald E. Knuth says, “In contrast to the unsymmetric relationship between a main routine and a subroutine, there is complete symmetry between coroutines, which call on each other.”[24]

Coroutines are handy for implementing ...

Get Programming Groovy 2 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.