Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1
Chapter 4

[ 59 ]

No matter what value is contained in the last statement in a method, if the return
type is void, the value returned will always be null:


void returnVoid(param) {
param
}

when: "calling a method with void return, passing String"
def result = returnVoid("Fred")
then: "type of returned value is null"
!result
result == null

when: "calling a method with void return, passing Integer"
result = returnVoid(123)
then: "type of returned value is null"
!result
result == null

Properties and GroovyBeans


We know from Java that a JavaBean is a class that implements getters and setters for
some or all of its instance fields. Groovy automatically generates getters and setters
for instance fields in a class that have the default visibility of public. It also generates
a default constructor. This means that a Groovy class is automatically accessible as
a JavaBean without any additional coding. Instance fields that have automatically
generated getters and setters are known in Groovy as properties, and we refer to these
classes as GroovyBeans, or by the colloquial POGO (Plain Old Groovy Object):


given: "a Groovy class"
Customer customer = new Customer()
when: "we set a value via the Setter"
customer.setName "Brian Beausang"
then: "we can use either the getter or property notation"
"Brian Beausang" == customer.getName()
customer.getName() == customer.name
when: "we set a value via property notation"
customer.name = "Carol Coolidge"
then: "we can use either the getter or property notation
"Carol Coolidge" == customer.name
Free download pdf