Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

The Groovy Language


[ 84 ]

Operator overloading

Java inherited many features from the C++ language, with one notable exception—
operator overloading. Groovy implements operator overloading as a language
feature, which means that any class can implement its own set of operators. In the
simplest case, we can overload the arithmetic operators and make any object of the
class behave as if it is a numeric value. Operators are overloaded by implementing
the corresponding operator method in the class, for example, the plus() method to
implement addition.


The Groovy version of the Date class implements some operators, including the
plus() and minus() operators. Operator overloading is a fundamental feature in
implementing DSLs, so we will go into this feature in significant detail later in
the book:


given:
def today = new Date()
def tomorrow = today + 1
def yesterday = today - 1
expect:
today.plus(1) == tomorrow
tomorrow.minus(1) == today
today.minus(1) == yesterday

Summary


In this chapter, we conducted a whistle-stop tour of the Groovy language. We
touched on most of the significant features of the language as a part of this tour.


In the subsequent chapters, we will delve deeper into some of these features, such as
operator overloading. We will also cover some of the more advanced features that
have not been touched on here, such as builders and metaprogramming. However,
this book is not intended to be a complete tutorial on the Groovy language, and I
recommend you delve further into the language by reading the Groovy user guide,
which is available at http://www.groovy-lang.org/documentation.html.


http://www.ebook3000.com
Free download pdf