This chapter covers
- Why you want to have closures
- How to declare and use closures
- How to design methods that make use of closures
I wouldn’t like to build a tool that could only do what I had been able to imagine for it.
Bjarne Stroustrup
Closures are important. Very important. They’re arguably one of the most useful features of Groovy. But at the same time they can be a strange concept until you fully understand them. To get the best out of Groovy, or to understand anyone else’s Groovy code, you’re going to have to be comfortable with closures. Not just “met them once at a wedding” comfortable, but “invite them over for a barbecue on the weekend” comfortable.
Now, we don’t want to scare you away. Closures aren’t hard—they’re just different than anything you might be used to. In a way, this is strange, because one of the chief tenets of object orientation is that objects have behavior as well as data. Closures are objects of which the main purpose in life is their behavior—that’s almost all there is to them.
In previous chapters, you’ve seen a few uses of closures, so you might already have a good idea of what they’re about. Please forgive us if we seem to be going over the same ground again—it’s so important, we’d rather repeat ourselves than leave you without a good grasp of the basic principles.