Its purpose is to have a null object instead that a null
keyword.
In normal Java null
is a special keyword that it's used to mean that the reference isn't attached to any object.. this works fine but it doesn't handle situations in which you try to do something with a null reference.
Since a null reference is not an object you can't do anything on it and Java will throw a NullPointerException
. On the opposite hand if you have a NullObject
your reference will point to this one instead that to nothing.. of course this NullObject
is not able to do anything, when you'll try to invoke a method on it nothing will happen but no exception will be thrown because althrough NullObject
means "absence of any object" it's implemented as an object with the obvious conseguence to avoid these situations.
So that groovy can handle things like object?.methodName()
. If object is null groovy will use a NullObject
so that this implicit check will do something like (maybe this is not the actual implementation, is just to give you the idea)
if (object instanceof NullObject)
return new NullObject();
else
return object.someMethod();
In conclusion it is needed to overcome the fact that using a null reference in Java will always cause a NullPointerException
.