Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

The Groovy Language


[ 62 ]

Here, we are asserting a value within a complex structure of arrays and maps.
Groovy will happily breakdown each element of the structure in the assertion
output, as follows:


Assertion failed:

assert map.c.e[1] == 'h'
| | || |
| | |g false
| | [f, g]
| [d:d, e:[f, g]]
[a:a, b:b, c:[d:d, e:[f, g]]]

From time to time in the text, we will use assertions as a shorthand means of
validating and illustrating the code. For instance, in the Account examples, we could
have illustrated setting and getting property values using assertions as follows:


Customer customer = new Customer()
customer.setName("Carol Coolidge")
assert customer.name == customer.getName()

Autoboxing


Java has two ways of handling numeric values. We can either use the numeric
primitive types, such as int, float, double, and so on, or their equivalent classes,
such as Integer, Float, Double, and so on. Unfortunately, you can't put an int
or any other primitive type into a collection; so you must box the int object into
an Integer object to put it into the collection, and unbox it if you need to use the
primitive int type again.


From Java 1.5 onwards, Java introduced the concept of autoboxing, whereby
primitive types are automatically promoted to their object-based equivalent when
the need arises. Groovy goes a step further with the autoboxing concept. In essence,
Groovy behaves as if primitives don't exist. Numeric fields of classes are stored as
the declared primitive type; however, as soon as we make use of that variable and
assign it to a local variable, it is automatically converted to the equivalent wrapper
type object. Even numeric literals behave like objects:


expect: "numeric literal is implemented with Numeric class"
2.0 instanceof BigDecimal
2 instanceof Integer
2.00000f instanceof Float
2l instanceof Long

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