Reputation: 305
This example can be easily tested in the groovy console.
var a is evaluated to not null while b is evaluated to null.
Both are instances of org.codehaus.groovy.runtim.NullObject
def b = null
println b.getClass()
println b == null
def a = null.getClass().newInstance()
println a.getClass()
println a == null
Does anyone knows why?
This is a tricky thing when dealing with reflection code.
Upvotes: 2
Views: 530
Reputation: 6508
Actually I am wondering if this is not a bug. As an explanation... NullObject is a runtime/intermediate kind of Object. If you do anything on null, then NullObject is used. This, and the the implementation of NullObject#equals speaks for a==null returning true. It returns fails, because there is some internal code before that, that is for example determining if compareTo is called instead of equals and such things. Now this piece of code starts with
if (left == right) return true;
if (left == null || right == null) return false;
so null==null will return true, but NullObject==null will return false. On the other hand NullObject should not leak out if possible. Maybe we should fix newInstance() to return null.
I filled http://jira.codehaus.org/browse/GROOVY-5769 for this
Upvotes: 1
Reputation: 171084
In the equals method of NullObject, it only returns true
if you are comparing it to null
As an instance of NullObject
is not strictly null
, it returns false...
Whether NullObject
should return true
if you call equals
against another NullObject
is probably a question best asked on the mailing list... I'll have a look and see if I can find any previous question.
Upvotes: 0