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

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

问题描述

在 Groovy 中,return 语句是可选的,允许您编写如下方法:

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

...添加 ab 并将结果返回给调用者.

但是,我想知道当方法具有多个返回语句"时的语义是什么.例如,在 Java 中,您可能有:

字符串追加(字符串 a,字符串 b){如果(a == null){返回 b;}返回 a + b;}

这可以(假设地)被翻译成 Groovy,比如:

def append(a, b) {如果一个) {b}a + b}

但是,在这种情况下,Groovy 如何知道 if 语句中的 b 应该被返回?还是没有?我假设 Groovy 不能简单地将结果未使用的任何语句视为 return,对吗?在这种情况下,可选返回"功能的行为方式是否有任何明确定义的语义?

解决方案

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

<块引用>

请注意,方法末尾的 return 语句是可选的.

因此,该 if 块中的 b 将永远不会被返回,除非您明确返回它.在实践中,这意味着返回值将是评估的最后一条语句的结果,所以如果您的示例是

def append(a, b) {如果 (!a) { b }否则 { a + b }}

如果 !atrue 则结果为 b,否则为 a + b.p>

调用void函数的结果是null,所以如果例子是

def append(a,b) {如果 (!a) { b }否则 { a + b }println "调试:$a $b"}

然后 append 将始终返回 null.

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

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

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

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

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

This could (hypothetically) be translated to Groovy like:

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

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:

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.

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

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