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

前端 未结 2 567
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-11 12:02

I have this test code:

def test = null

test.each {  } 

Why don\'t I get any exception?

2条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-11 12:54

    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

提交回复
热议问题