【问题标题】:In the below code function is returning value of variable a, how is it possible, please explain在下面的代码中,函数是变量a的返回值,怎么可能,请解释
【发布时间】:2015-02-03 08:37:19
【问题描述】:

下面代码函数myprint是返回变量a的值,怎么可能,请解释一下

class Test {  
    def myprint(){        
        def a = "my"  
        }   
        }
        def test1 = new Test()
        log.info test1.myprint()

【问题讨论】:

标签: groovy


【解决方案1】:

你遇到了一个没有 return 语句的 groovy 方法。

确实,正如Groovy Goodness 中所说,作为一个例子,return 语句对于结束一个 Groovy 方法不是强制性的:最后执行指令的结果用作方法返回值。

因此,写作

def myMethod() {
    def a = "value"
}
println myMethod()

会输出

value

因为 Groovy 解释器会将 def a = "value" 作为最后一条指令视为方法返回值。

但是,为了清楚起见,与 groovy 委员会相反,我建议您不要使用该功能,因为它会使代码的可读性降低。

加分点:这个功能非常适合闭包:当调用 [1,2,3].collect { it*2} 时将返回 [2, 4, 6],这非常好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-06
    相关资源
    最近更新 更多