Search code examples
groovyclosures

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()?

Solution

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