DevOps / Apache Groovy Interview questions
Explain the execution flow of currying in a Groovy closure?
Currying, via a closure's curry() method, produces a new closure with one or more of the original closure's leading parameters pre-filled with fixed values, reducing the number of arguments the resulting closure still expects when it's eventually called.
Internally, calling curry(value) doesn't invoke the original closure immediately - it wraps the original closure in a new curried closure object that remembers the supplied value(s) and the original closure reference, deferring actual execution until the curried closure itself is finally called with its remaining arguments.
When the curried closure is eventually invoked with the rest of the arguments, it combines the previously curried, fixed, values with the newly supplied ones, in the correct parameter order, and only then delegates to the original closure's actual body with the complete, combined argument list.
Groovy also supports rcurry(), which curries from the right/trailing parameters instead of the left/leading ones, and ncurry(), which curries starting at a specific parameter index, giving flexibility in which parameters get pre-filled rather than always being restricted to the leftmost ones.
This is commonly used to specialize a general-purpose closure into a more specific one - for example, currying a generic add(a, b) closure with a fixed first value produces a reusable "add5" closure - without writing a separate, explicitly named closure for each specialized variant.
flowchart LR A[Original closure: add a,b] --> B[Call curry 5] B --> C[New curried closure: remembers value 5] C --> D[Later call: curried closure with b] D --> E[Combine 5 and b, delegate to original closure body]
More Related questions...