Reputation: 696
I am trying to predict the behavior of this code in Groovy
userList.find { }
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?
null
is returned?.find()
?Upvotes: 2
Views: 4197
Reputation: 93561
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()
Upvotes: 0
Reputation: 1503769
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
.
Upvotes: 7