Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

The Groovy Language


[ 58 ]

The preceding method returns String object, while the type of the object passed in
is dynamic, so Groovy will attempt to coerce the return object to a String and return
that value:


when: "calling a method with a typed return"
def result = returnString("Fred")
then: "type of returned value is String"
result instanceof String

when: "we pass the same function an Integer"
result = returnString(123)
then: "the type returned is still String"
result instanceof String
result == "123"

No matter what type of object we try to return, the return type defined in the method
will determine the type that is actually returned:


String returnIntegerCoercedToString(Integer param) {
param
}

when: "we pass a typed Integer"
result = returnIntegerCoercedToString(123)
then: "the type returned is still String"
result instanceof String
result == "123"

However, if the method uses the def keyword as its return type, then the return type
is considered to be dynamic, so the type we get back is determined by the type of the
returned object:


def returnDef(param) {
param
}
when: "calling a method with dynamic return type"
def result = returnDef("Fred")
then: "type of returned value is String"
result instanceof String

when: "we pass the same function an Integer"
result = returnDef(123)
then: "the type returned is Integer"
result instanceof Integer
result == 123

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