Closures and DSLs
The with method helps delegate calls within a closure, giving us an execution context. We can take advantage of this approach to create our own methods with context and fluency.
Let’s revisit the pizza-ordering example. Say we want to create a syntax that flows naturally. We don’t want to create an instance of PizzaShop because that is more of an implementation detail. We want the context to be implicit. Let’s look at the following code (in the next section we’ll see how to make this more fluent and context-driven):
CreatingDSLs/ClosureHelp.groovy | |
| time = getPizza { |
| setSize Size.LARGE |
| setCrust Crust.THIN |
| setTopping "Olives", "Onions", "Bell Pepper" |
| setAddress "101 Main St., ..." |
| setCard(CardType.VISA, ... |
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.