Groovy's “optional return” semantics

前端 未结 1 1872
心在旅途
心在旅途 2021-01-17 10:10

In Groovy, the return statement is optional, allowing you to write methods like:

def add(a, b) {
    a + b
}

...which adds a a

相关标签:
1条回答
  • 2021-01-17 10:20

    The page you linked (rather tersely) describes the exact semantics:

    Notice that the return statement is optional at the end of methods.

    So the b in that if block would never be returned unless you explicitly returned it. In practice this means that the return value will be the result of the last statement evaluated, so if your example were

    def append(a, b) {
       if (!a) { b }
       else { a + b }
    }
    

    Then the result would be b if !a is true and a + b otherwise.

    The result of a call to a void function is null, so if the example were

    def append(a,b) {
       if (!a) { b }
       else { a + b }
       println "debug: $a $b"
    }
    

    Then append would always return null.

    My own rule of thumb for this is to always use an explicit return statement if the method or closure contains more than one statement. I think relying on the implicit return statement in more complex methods is dangerous since if anyone adds a line to the end of the method they will change the return value even though they most likely didn't intend to.

    0 讨论(0)
提交回复
热议问题