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

自作多情 提交于 2020-01-11 04:27:05

问题


I have this test code:

def test = null

test.each {  } 

Why don't I get any exception?


回答1:


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




回答2:


A null value when using the each closure is the same as a collection with 0 elements. If you have the code

def test=null
test.each {println "In closure with value "+it}

The print statement won't execute. If you change test to

def test=[1,2,3]

you will get output.



来源:https://stackoverflow.com/questions/5472795/why-dont-i-get-a-nullpointerexception-in-groovy-in-this-case

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!