Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why don't I get a NullPointerException in Groovy in this case?

Tags:

null

groovy

I have this test code:

def test = null

test.each {  } 

Why don't I get any exception?

like image 842
res1 Avatar asked Mar 29 '11 12:03

res1


People also ask

Does Groovy have null?

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.

How do I stop the NullPointerException in Groovy?

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

Is null false in Groovy?

A null object always coerces to false.


1 Answers

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

like image 183
Dónal Avatar answered Sep 21 '22 01:09

Dónal