简体   繁体   English

空闭包的 Groovy 真相是什么?

[英]What is the Groovy truth of an empty closure?

I am trying to predict the behavior of this code in Groovy我试图在 Groovy 中预测这段代码的行为

userList.find { }

.find documentation .查找文档

When the find method is invoked and passed a closure it returns the first element that evaluates the closure into Groovies understanding of true .find方法被调用并传递一个闭包时,它返回将闭包计算为 Groovies 对true理解的第一个元素。 When the find method is called without any parameters it returns the first object in the list that matches true according to Groovy truth.当不带任何参数调用find方法时,它返回列表中第一个根据 Groovy 真理匹配为true对象。

What happens if an empty closure is used?如果使用空闭包会发生什么?

  1. Will it evaluate to true and thus the first element of the list is returned?它会评估为真,从而返回列表的第一个元素吗?
  2. Will it always evaluate to false and after iterating over the list null is returned?它是否总是评估为 false 并在迭代列表后返回null
  3. Will it be behave like .find() ?它的行为会像.find()吗?

From the Groovy Closures Formal Definition ( Alternative Source ): Groovy闭包的正式定义替代来源 ):

Closures always have a return value. 闭包始终具有返回值。 The value may be specified via one or more explicit return statement in the closure body, or as the value of the last executed statement if return is not explicitly specified. 该值可以通过闭包主体中的一个或多个显式return语句指定,或者如果未显式指定return,则指定为最后执行的语句的值。 If the last executed statement has no value (for example, if the last statement is a call to a void method), then null is returned. 如果最后执行的语句没有值(例如,如果最后一个语句是对void方法的调用),则返回null。

And from Groovy Truth 来自Groovy Truth

Object references 对象引用
Non-null object references are coerced to true. 非空对象引用被强制为true。
... ...

 assert !null 

That suggests to me that the truth of the return value of an empty closure is always false, so find will never find anything, and thus presumably return null . 这向我暗示了,空闭包的返回值的真相始终为假,因此find永远找不到任何东西,因此可能返回null

there is no definition of "empty closure" only if you delegate this closure to a Map, then the Map keeps empty :只有当您将此闭包委托给 Map 时,才没有“空闭包”的定义,然后 Map 保持为空:

​Map closureToMap(Closure c, Map attrs=[:]) {
    c.resolveStrategy = Closure.DELEGATE_FIRST
    c.delegate = attrs
    c()
    return attrs
  }

def myEmptyClosure = {}
assert closureToMap(myEmptyClosure).isEmpty()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM