简体   繁体   中英

What is the Groovy truth of an empty closure?

I am trying to predict the behavior of this code in 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 . When the find method is called without any parameters it returns the first object in the list that matches true according to Groovy truth.

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?
  3. Will it be behave like .find() ?

From the Groovy Closures Formal Definition ( Alternative Source ):

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

And from Groovy Truth

Object references
Non-null object references are coerced to 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 .

there is no definition of "empty closure" only if you delegate this closure to a Map, then the Map keeps empty :

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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