July 2013
Intermediate to advanced
370 pages
8h 27m
English
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 |
| | |
Read now
Unlock full access