Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1
Chapter 1

[ 15 ]

Groovy operator overloading

Operator overloading is a powerful feature of the C++ language. Java inherited
many of the features of the C++ language, but operator overloading was significantly
left out. Groovy introduces operator overloading as a base language feature.


Any Groovy class can implement a full set of operators by implementing the
appropriate corresponding method in the class. For example, the plus operator is
implemented via the plus() method.


Regular expression support

Groovy builds regular expression handling right into the language via the =~
operator and matcher objects. The following example creates a regular expression to
match all multiple occurrences of the space character. This creates a matcher object
from this expression and applies it to a string by using the replaceAll method:


def lorem =
"Lorem ipsum dolor sit amet, consectetur adipisicing elit"
println lorem
def matcher = lorem =~ " +"
def removed = matcher.replaceAll(" ")
println removed

Optional syntax

Optional typing means that variable type annotations are optional. This does not
mean that variables have an unknown variable type. It means that the type will be
determined at run time based on the value that gets assigned to the variable. All of
the following are legal syntax in Groovy:


int a = 3
def b = 2
String t = "hello"
def s = 'there'

Trailing semicolons at the end of statements are optional. The only time that you
explicitly need to use a semicolon in Groovy is to separate statements that occur on
the same line of code, as shown in the first and third lines in the following code:


int a = 3; int b = 4;
def c = 2
def d = 5; def e = 6
Free download pdf