I have this test code:
def test = null
test.each { }
Why don't I get any exception?
In Groovy we can do this shorthand by using the null safe operator (?.). If the variable before the question mark is null it will not proceed and actually returns null for you.
Fortunately, with Groovy this is very easy. Use the Safe Navigation (or null-safe) operator which guards against NullPointerExceptions. This is just a question mark (?) before the dot (.)
A null object always coerces to false.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With