The implementation of each tries to call the iterator method of it's target in a null-safe fashion. If each is called on a null object, or an object without an iterator method, nothing happens.
I haven't seen the source code, but it could look something like this§
Object each(Closure closure) {
if (this?.respondsTo("iterator")) {
def iterator = this.iterator()
while (iterator.hasNext() {
def item = iterator.next()
closure(item)
}
}
return this
}
§ In reality, this method is probably written in Java rather than Groovy
The implementation of
each
tries to call theiterator
method of it's target in a null-safe fashion. Ifeach
is called on a null object, or an object without aniterator
method, nothing happens.I haven't seen the source code, but it could look something like this§
§ In reality, this method is probably written in Java rather than Groovy
A null value when using the each closure is the same as a collection with 0 elements. If you have the code
The print statement won't execute. If you change test to
you will get output.