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

前端 未结 2 580
爱一瞬间的悲伤
爱一瞬间的悲伤 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:34

    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.

提交回复
热议问题