Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

The Groovy Language


[ 54 ]

Implicit imports

Java automatically imports the java.lang package for you. Groovy goes a step
further and automatically imports some of the more commonly-used Java packages,
as follows:



  • java.lang.*

  • java.util.*

  • java.net.*

  • java.io.*

  • java.math.BigInteger

  • java.math.BigDecimal


Two additional packages from the Groovy JDK (GDK) are also imported:



  • groovy.lang.*

  • groovy.util.*


Default visibility, optional semicolon

The majority of classes that I have written in Java have been declared public. Java
requires us to always explicitly express the public visibility of a class. This is because
the default visibility of classes is "package private", which, to be honest, is a visibility
that is seldom used and is often misunderstood. "Package private" visibility means
classes are accessible by other classes in the same package, but not by classes in
other packages. Groovy makes the more sensible decision that public visibility is
the default visibility, so it does not need to be stated in the class definition.


Java uses the semicolon to separate statements even when they end on the same
line. In Groovy, semicolons are optional as long as we limit ourselves to a single
statement per line. This small change makes for much cleaner looking code:


def customer = new Customer(id:1,name:"Aaron Anderson")
def savings = new Account(id:2, balance:0.00, owner:customer)

The previous snippet from our Account example would have been more
syntactically verbose in Java, without adding to the clarity of the code:


Customer customer = new Customer(id:1,name:"Aaron Anderson");
Account savings = new Account(id:2, balance:0.00, owner:customer);

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