Book Image

Groovy for Domain-Specific Languages, Second Edition

By : Fergal Dearle
Book Image

Groovy for Domain-Specific Languages, Second Edition

By: Fergal Dearle

Overview of this book

Table of Contents (20 chapters)
Groovy for Domain-specific Languages Second Edition
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Preface
Free Chapter
1
Introduction to DSLs and Groovy
Index

Closure return values


Closure declarations syntax provides no means of defining a return value. Every closure does, however, return a value with each invocation. A closure can have explicit return statements. If a return statement is encountered, then the value defined in the return statement is returned; otherwise, execution continues until the last statement in the closure block:

given: "a closure that returns values"
def closure = { param ->
    if (param == 1)
        return 1
    2
}
expect:
closure(1) == 1  // return statement reached
closure(-1) == 2 // ending statement evaluates to 2

If no return statement is encountered, then the value returned by the closure is the result of evaluating the last statement encountered in the closure block. If the last statement has no value, the closure will return null:

void voidMethod() {
}
given: "a closure returning void method"
def nullReturn = { voidMethod() }
expect:
nullReturn() == null