Command chains

We already knew that Groovy allows us to leave out parentheses when calling methods. Another neat trick introduced in Groovy 1.8 is the ability to leave out the dot when we chain method calls. Using this feature, we can further improve the readability of our DSLs by adding constructs that mimic natural language. Take the following chained method calls:

deposit (100.00).currency(USD).to(savings)

By leaving out the parentheses on these calls and the intervening dots we can express this chain as follows:

deposit 100.00 currency GBP to savings

Building this mini DSL is relatively straightforward. First we need an enum for currencies, which we statically import. We also define two method calls, convert and deposit:

enum Currency { USD, GBP, ...

Get Groovy for Domain-specific Languages - Second Edition 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.