Versions Compared


  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 5.3

Since Groovy 1.6, it is possible for if/else and try/catch/finally blocks to return a value when they are the last expression in a method or a closure. No need to explicitly use the return keyword inside these constructs, as long as they are the latest expression in the block of code.

As an example, the following method will return 1, although the return keyword was omitted.

Code Block
def method() {
    if (true) 1 else 0

assert method() == 1

For try/catch/finally blocks, the last expression evaluated is the one being returned. If an exception is thrown in the try block, the last expression in the catch block is returned instead. Note that finally blocks don't return any value.

Code Block
def method(bool) {
    try {
        if (bool) throw new Exception("foo")
    } catch(e) {
    } finally {

assert method(false) == 1
assert method(true) == 2