Groovy的“可选返回”语义 [英] Groovy's "optional return" semantics

查看:125
本文介绍了Groovy的“可选返回”语义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Groovy中, return语句是可选的,允许您编写像:

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

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

...添加 a b 并将结果返回给调用者。

...which adds a and b and returns the result to the caller.

然而,我想知道什么时候该方法有多个返回语句的语义。例如,在Java中你可能有:

However, I'm wondering what the semantics are when the method has multiple return "statements". For example, in Java you might have:

String append(String a, String b) {
    if (a == null) {
        return b;
    }
    return a + b;
}

这可以(假设)转换为Groovy:

This could (hypothetically) be translated to Groovy like:

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

然而,在这种情况下,Groovy如何知道<$ c如果应该返回语句,那么code> b 在内部?或者不是?我认为Groovy不能简单地将其结果未被使用的语句视为 return ,是正确的吗?在这种情况下,可选返回功能的行为有没有明确定义的语义?

However, in this case, how does Groovy know that b inside of the if statement should be returned? Or does it not? I assume that Groovy cannot simply treat any statement whose result is unused as a return, correct? Are there any clearly defined semantics for how the "optional return" feature behaves in this case?

推荐答案

您链接的页面(相当简洁)描述了确切的语义:

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


请注意,return方法在方法结束时是可选的。

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

c $ c> b 中,如果块永远不会被返回,除非你明确地返回它。在实践中,这意味着返回值将是最后一条语句评估的结果,所以如果你的例子是

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 }
}

如果!a 是<$ c,那么结果将会是 b $ c> true a + b 否则。

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

呼叫的结果到 void 函数是 null ,所以如果这个例子是

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"
}

然后追加总会返回 null

我自己的经验法则是始终使用显式如果方法或闭包包含多个语句,则返回语句。我认为在更复杂的方法中依赖隐式return语句是很危险的,因为如果有人在方法的末尾添加一行,他们将会改变返回值,即使它们很可能不打算。

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.

这篇关于Groovy的“可选返回”语义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆