The Parentheses Limitation and a Workaround
Let’s leave the pizza example behind and look at a simple register. This section will show how to create a DSL for a simple register, the device that lets us total amounts. Here is the first attempt to create that:
CreatingDSLs/Total.groovy | |
| value = 0 |
| def clear() { value = 0 } |
| def add(number) { value += number } |
| def total() { println "Total is $value" } |
| |
| clear() |
| add 2 |
| add 5 |
| add 7 |
| total() |
The output from the previous code is as follows:
| Total is 14 |
In this code, we wrote total and clear instead of total and clear, respectively. Let’s drop the parentheses and try to call total:
CreatingDSLs/Total.groovy | |
| try { |
| total |
| } catch(Exception ex) { |
| println ex |
| } |
Executing the ...
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.